I write a list by C language. But it can not get the last number. The program accept some number when the number is not 0
. And put number into a list. This is code:
#include <stdio.h>
#include <stdlib.h>
typedef struct List{
int data;
struct List *next;
}List;
void initList(List **pList)
{
*pList = NULL;
}
List *createList(List *pHead)
{
List *p1, *p2;
p1 = p2 = (List *)malloc(sizeof(List));
if(p1 == NULL || p2 == NULL) {
exit(0);
}
scanf("%d", &p1->data);
p1->next = NULL;//create a node
while(p1->data != 0) {
if (pHead == NULL){
pHead = p1;
}else{
p2->next = p1;
}
p2 = p1;
p1 = (List *)malloc(sizeof(List));
scanf("%d", &p1->data);
p1->next = NULL;
}
return pHead;
}
void printList(List *pHead)
{
if(pHead == NULL){
printf("empty");
}else{
while(pHead->next != NULL){
printf("%d ", pHead->data);
pHead = pHead->next;
}
}
}
int main()
{
List *pList = NULL;
initList(&pList);
pList = createList(pList);
printList(pList);
return 0;
}
The program returns 1 2 3
when I input 1 2 3 4 0
. Could someone give me some advice? Thanks a lot!