Print an ordered linked list

后端 未结 2 355
南旧
南旧 2021-01-23 13:27

Just did some editing on it, i tried what you said but it didnt work, so i tried something i am a little more familiar with but it doesnt seem to work correctly. It prints the i

2条回答
  •  攒了一身酷
    2021-01-23 13:32

    int printList(struct listNode * Head){
    struct listNode *current = Head;
    while (Head != NULL){
          printf("%d \n", *current);
          current = current->next;
    }
    

    You're pretty close.

    Take a look at the condition on your while loop - the reason your program crashes is that 'Head' is never updated, so the condition is always true. So the program just keeps setting 'current' equal to 'current->next' without stopping until you get to the end of your list, at which point 'current->next' is NULL and the program crashes.

    If you change your while loop to check whether 'current' is NULL instead of 'Head', it will stop when it reaches the end of the list and your program won't crash.

    EDIT: Adding some pointers on fixing the extra zeroes showing up the linked list.

    struct listNode Head = {0, NULL};
    

    At the beginning of your program, you're creating a node in your linked list with the value 0. So you've always got at least one 0 no matter what your input is. You might consider initializing Head to NULL instead. If you do that, you'll have to check for that condition in your insertNode function.

    You're also getting some extra zeroes because you're checking your loop condition ('while(x > 0)') before you get the input that you use to make that decision ('scanf("%d", &x);'). You might want to consider changing that order by using a 'do...while' instead of 'while'. Take a look at http://www.cprogramming.com/tutorial/c/lesson3.html for an explanation of 'do...while' with examples.

提交回复
热议问题