I am writing a few functions for link lists, but I can't get these to work, and I can't see what the problem is. The NewList() function works, but the other two don't. If I use these functions to make two lists which are linked, then they end up pointing to each other, and so the linked lists makes a cycle.
Code:
struct DATA {
int val;
struct DATA *link;
};
typedef struct DATA INFO;
typedef INFO *LISTPTR;
LISTPTR NewList(void);
LISTPTR AddListStart(LISTPTR base);
LISTPTR AddListEnd(LISTPTR base);
LISTPTR NewList(void)
{
LISTPTR base=NULL;
base = (LISTPTR)malloc(sizeof(INFO));
if(base != NULL) {
base->link = NULL;
return base;
}
return NULL;
}
LISTPTR AddListEnd(LISTPTR base)
{
LISTPTR temp=NULL;
LISTPTR current=NULL;
if(base != NULL) {
current = base;
while(current->link != NULL) {
current = current->link;
}
temp = (LISTPTR)malloc(sizeof(INFO));
if(temp != NULL) {
current->link = temp;
temp->link = NULL;
}
}
FreePointers(temp, current, NULL);
return base;
}
LISTPTR AddListStart(LISTPTR base)
{
LISTPTR temp;
LISTPTR current;
if(base == NULL) {
// This function doesn't start a new list, NewList() does that
}
else {
temp = (LISTPTR)malloc(sizeof(INFO));
if(temp != NULL) {
temp->link = base;
base = temp;
}
}
FreePointers(temp, current, NULL);
return base;
}