why the tail of this autoexpand list can't successfully display?

Viewed 56

I want to use carriage return to end up input,but why the list lost its last element. I have check my code but can't figure out why the NUll was pointed by the penult instead of the last one. The first function is to automatically establish the list, and I use \n as the sign to end up input.

#include <stdio.h>
#include <stdlib.h>

typedef struct number {
    int num;
    struct number* pnext;
} number;
number* autoexpand()
{
    char c;
    int n = 0;
    number *head = NULL, *p1, *p2;
    p1 = p2 = (number*)malloc(sizeof(number));
    scanf("%d", &p1->num);
    while (c = getchar() != '\n') {
        n++;
        if (n == 1) {
            head = p1;
        }
        else {
            p2->pnext = p1;
        }
        p2 = p1;
        p1 = (number*)malloc(sizeof(number));
        scanf("%d", &p1->num);
    }
    p2->pnext = NULL;
    return head;
}
void print(number* p)
{
    for (; p != NULL; p = p->pnext) {
        printf("%d ", p->num);
    }
    printf("\n");
}
int main()
{
    number *p, *q;
    p = autoexpand();
    print(p);
    for (; p != NULL;) {
        q = p;
        p = p->pnext;
        free(q);
    }
}

Output:

5 4 3 2 1
5 4 3 2
1 Answers

I have to admit that the use of getchar + scanf is a bit confusing to me.

I haven't tested the program but I can see the following bug in the code:

At the end of the function you are missing the last pointer p1, when you go out of the while loop you should save p1 and then add NULL as tail.

p2->pnext = p1;
p1->pnext = NULL;
return head;

I think it should do the trick.

Related