简体   繁体   中英

traversing through the linked list and returning the char* values

I am having problem returning char* values from the linked list can someone please please help How can i return char* values within a while loop? When i try to run my program i get a single value from my linked list looping forever with the following code:

char * list_next(list *l)
{    
   list *currentPosition = NULL;    
   currentPosition = l->next; //skipping dummy value in the singly linked list

  while (currentPosition != NULL)
  {
    currentPosition = currentPosition->next;
    return currentPosition->charValue;

  }

   return NULL;
}

this is how i am calling the function:

char * item;
while(item = list_next(list))    
printf("%s ",item);

it would be easier to do something like

list* current = list->next; //skip the dummy

while(current)
{
    printf("%s ", current->charValue);
    current = current->next;
}

But since you have to do it with a function and to do it in the format you've got you'd do something like the following:

char* list_next(list **l)
{    
  if (*l != NULL)
  {
    char* value = (*l)->charValue;
    *l = (*l)->next;
    return value;
  }

   return NULL;
}

and call it like so

list* temp_list = my_list->next; //skip the dummy

char * item;
while(item = list_next(&temp_list))    
    printf("%s ",item);

You can only return 1 value from a function. To make recurring calls to the function like you originally had in your while loop to move through the entire list you have to modify the input parameter so the next call in the while loop operates on the next element in the list. Notice the ** in the function parameters.

You are returning in the middle of the loop, so you don't get a chance to process the other nodes.

You need to change something to process multiple characters. You could collect them into an array, but that introduces the problem of needing to know in advance how many items are in the list. You could process the items inline, as ThePosey suggests.

But if you want the function to be list_next and return one item each time, then you need to 'return' two things: the list value, and the list pointer. One way would be to modify the function signature: char * list_next(list **l) . If you pass in a pointer to a pointer, the function can use it as an out parameter and set it to the next node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM