用C程序打印列表不能打印最后一个数字

用C程序打印列表不能打印最后一个数字,c,linux,C,Linux,我用C语言写了一个列表。但它无法获取最后一个数字。当数字不是0时,程序接受某个数字。然后把数字写进一个列表。这是代码: #include <stdio.h> #include <stdlib.h> typedef struct List{ int data; struct List *next; }List; void initList(List **pList) { *pList = NULL; } List *createList(Lis

我用C语言写了一个列表。但它无法获取最后一个数字。当数字不是
0
时,程序接受某个数字。然后把数字写进一个列表。这是代码:

#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;
}
#包括
#包括
类型定义结构列表{
int数据;
结构列表*下一步;
}名单;
无效初始列表(列表**pList)
{
*pList=NULL;
}
列表*createList(列表*pHead)
{
列表*p1,*p2;
p1=p2=(列表*)malloc(sizeof(列表));
如果(p1==NULL | | p2==NULL){
出口(0);
}
scanf(“%d”,&p1->data);
p1->next=NULL;//创建一个节点
而(p1->数据!=0){
如果(pHead==NULL){
pHead=p1;
}否则{
p2->next=p1;
}
p2=p1;
p1=(列表*)malloc(sizeof(列表));
scanf(“%d”,&p1->data);
p1->next=NULL;
}
返回pHead;
}
无效打印列表(列表*pHead)
{
如果(pHead==NULL){
printf(“空”);
}否则{
while(pHead->next!=NULL){
printf(“%d”,pHead->data);
pHead=pHead->next;
}
}
}
int main()
{
List*pList=NULL;
initList(&pList);
pList=createList(pList);
打印列表(pList);
返回0;
}

当我输入
12340
时,程序返回
1233
。有人能给我一些建议吗?非常感谢

只需检查
pHead
是否为
NULL
,而不是
pHead->next
。当您选中
pHead->next
时,您将从循环的顶部退出,而不会打印最后一个元素

void printList(List *pHead)
{
    if(pHead == NULL){
        printf("empty");
    }else{
        while(pHead != NULL){
            printf("%d ", pHead->data);
            pHead = pHead->next;
        }
    }

}
p1
p2
指向同一位置

此语句为
列表
分配内存,并分配给
p2
,相同的值分配给
p1

分别为
p1
p2
p1=malloc(sizeof(List)); p2=malloc(sizeof(List))


不需要类型转换。

使用
gcc-Wall-Wextra-g
编译;然后学习如何使用
gdb
调试器!请注意,您应该
p1 = p2 = (List *)malloc(sizeof(List));