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