gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:53 24 4
gpt4 key购买 nike

我用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;
}

当我输入 1 2 3 4 0 时,程序返回 1 2 3。有人可以给我一些建议吗?非常感谢!

最佳答案

只需检查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;
}
}

}

关于c - 用C程序打印列表不能打印最后一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24156537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com