gpt4 book ai didi

c - 单向链表的展示

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

我正在尝试创建一个单向链表。我创建了五个节点并用一个整数值对它们进行了初始化。但是当我打印链接列表时,我什么也得不到。

typedef struct node {
int value;
struct node* nextPtr;
} node;

node *nodePtr;
node *head;

void initializeLinkedList() {
static unsigned int i;

nodePtr = (node*)malloc(sizeof(node));
i = 0;

nodePtr->nextPtr = (node*)malloc(sizeof(node));
nodePtr->value = i;
head = nodePtr;
for (i = 1; i < 5; i++) {
nodePtr->nextPtr = (node*)malloc(sizeof(node));
nodePtr->value = i;
}
nodePtr->nextPtr = NULL;
}

void printLinkedList() {
static unsigned int i;

i = 0;
nodePtr = head;
while (nodePtr->nextPtr != NULL) {
printf("Value of ptr is %p \n", nodePtr->nextPtr);
printf("Value is %d \n", nodePtr->value);
}
}

我想我没有正确设置指针。

最佳答案

这个:

for (i = 1; i < 5; i++) {
nodePtr->nextPtr = malloc(sizeof(node));
nodePtr->value = i;
}

分配一个节点四次,然后它总是覆盖相同的元素,因为您没有更新 nodePtr。应该是

for (i = 1; i < 5; i++) {
nodePtr->nextPtr = malloc(sizeof(node));
nodePtr->value = i;
nodePtr = nodePtr->nextPtr;
}

相反(不仅仅是在这种特殊情况下 - 在您的代码中到处寻找并修复它,否则您最终会得到所有这些或多或少有趣的未定义行为结果......)。

此外,在printLinkedList()中,

while(nodePtr->nextPtr != NULL)

应该是

while(nodePtr != NULL)

否则你将在最后一次迭代时取消引用 NULL(和 BANG!)

关于c - 单向链表的展示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820904/

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