Originally Posted by
robwhit
any code?
The following program creates a list under your specifications, adds nodes in the head and deletes from head as well. The function that destroys the list is up to you to think of a way of doing it. Keep up, Bokarinho.
Code:
//------------------------------------------------------------------------------------------------//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
//------------------------------------------------------------------------------------------------//
typedef struct{
char *str;
int Len;
}string;
typedef struct linkNode{
string data;
struct linkNode * next;
}linkNode;
typedef struct{
linkNode *head;
}linklist;
linklist* CreateList()
{
linklist* l = malloc(sizeof(linklist));
if(l)
{
l->head = NULL;
return l;
}
else
return NULL;
}
//Function inserts a node into a single connected linked list.
void InsertNode(linklist *l, char *Val, int iLen)
{
//Pointer to head.
linkNode **ptrHeadNode = &l->head;
//Firstly create the node.
linkNode *p = malloc(sizeof(linkNode));
if(p == NULL)
{
printf("Memory Error.\n");
return;
}
else
{
//Initialise node.
p->data.str = strdup(Val);
p->data.Len = iLen;
//Set node to list.
p->next = *ptrHeadNode;
*ptrHeadNode = p;
}
}
//Prints a list using a double pointer, a simple pointer can be used.
void DumpList(linklist *l)
{
linkNode **ptrNode = &l->head;
printf("Dumping Linked List:\n");
for(; *ptrNode != NULL; ptrNode = &(*ptrNode)->next)
printf("%s %d\n", (*ptrNode)->data.str, (*ptrNode)->data.Len);
printf("\n\n");
}
void RemoveNode(linklist *l)
{
//Get a pointer to point the list head.
linkNode **ptrHead = &l->head;
//Save head node in n node.
linkNode *n = l->head;
//Set pointer to point the next item.
*ptrHead = (*ptrHead)->next;
//Delete node.
free(n);
}
void DeleteList(linklist *l)
{
//Deletes the whole list.
}
int main(int argc, char *argv[])
{
linklist *l = CreateList();
linkNode *pNode = NULL;
InsertNode(l,"test", 5);
InsertNode(l,"new", 10);
InsertNode(l,"delete", 15);
DumpList(l);
RemoveNode(l);
DumpList(l);
//DeleteList(l);
printf("Hit any key to continue..\n");
getch();
return 0;
}