Reputation: 3
I am trying to print the contents of a linked list which is a char* but the while loops are messing up the code:
the function to get the next item in a linked list:
char * list_next(list *l)
{
list *currentPosition = NULL;
currentPosition = l->next; //since the first node is a dummy value in the singly linked list
while (currentPosition != NULL)
{
return currentPosition->charValue;
currentPosition = currentPosition->next;
}
return NULL;
}
in my main:
char * item;
while(item = list_next(list))
printf("%s ",item);
can someone please help me I am pretty sure the problem is the returns inside the while loop but i cant seem to fix it
Upvotes: 0
Views: 176
Reputation: 29424
You've mentioned in a comment that you just need to return all values in the linked list.
function iterate(someNode)
if someNode ≠ null
node := someNode
do
do something with node.value [1]
node := node.next
while node ≠ someNode
From this Wikipedia article, CC BY-SA.
Now you could simply printf()
at position [1] in the code. However it seems that you have to return all values.
Therefore you have to create an (probably dynamic) array.
Upvotes: 0
Reputation: 12515
Your program, even with the return position swapped is still only going to print the "2nd" item in the list every time through - if it exists. You either need to work with a double pointer to update the base value, or come up with some better way to iterate your list.
Upvotes: 2
Reputation: 427
You pass the original list to list_next(). I believe you will always print the second item in a forever loop.
I suggest you can simplify it as below:
char *item;
for (item=list->next; // Skip the first item as you said the first node is dummy.
item != NULL; item=item->next) {
printf("%s ",item->charValue);
}
Upvotes: 0
Reputation:
Swap the two lines. return
immediately exits from the function. It should read
currentPosition = currentPosition->next;
return currentPosition->charValue;
instead.
(Not to mention numerous other errors that others pointed out as well - the lack of ability to actually update the next
pointer because of confusion about scopes, the missing check for NULL
before dereferencing, etc.)
Upvotes: 3