We have a problem with our LinkedList in C. When I count how many nodes should be in the list, I always get 1
LL count: 1
This is the Add, count and get last element of the list code:
void addLL(LL * head)
{
LL *newNode;
LL *tail = getLastNode(head);
newNode = malloc(sizeof(LL));
if(newNode != DEF_NULL)
{
newNode->ID=-1;
newNode->TCB=-1;
newNode->next = DEF_NULL;
if(!head) head = newNode;
else tail->next = newNode;
}
}
LL * getLastNode(LL * head)
{
LL *temp = head;
while(temp->next != DEF_NULL)
{
temp = temp->next;
}
return temp;
}
CPU_INT32U countLL(LL * head)
{
CPU_INT32U elements = 0;
LL * temp = head;
while(temp->next != DEF_NULL)
{
temp = temp->next;
elements++;
}
return elements;
}
It's called in this way:
addLL(list);
temp = countLL(list);
Debug_LOG("LL count: %i", temp);
where LL * list; is a global variable, and temp is in local scope. I hope anyone can see where I went wrong
Greetings, Sjaak and Gerrit
I see several issues in your code :
head
but the modification won't be propagated outside of the function. You should pass a "pointer to a list pointer" (i.e. aLL**
) that is equivalent to "the address of aLL*
"; See how I calladdLL()
and how I have modified its prototype and thehead
assignmentI propose the modified code that works for 1, 2 or any list length (I have just changed the
CPU_INT32U
toint
to compile quickly with MinGW, I could have typedef'ined):Output :