gpt4 book ai didi

c - 链表打印问题结构

转载 作者:行者123 更新时间:2023-11-30 14:35:54 25 4
gpt4 key购买 nike

我开发了一个链表,但是当我传递“head”作为参数来打印链表时,程序崩溃或返回垃圾内存数据。如果,我传递“middle”作为参数列表,则可以正常工作,并返回存储在中间和最后一个结构节点中的数据。使用Visual Studio 2017专业版在Windows 10专业工作站上进行开发。

我已粘贴完整的代码以供您反馈。谢谢!

  // A single linked list 
#include<stdio.h>

struct Node
{
int data;
struct Node* next;
};

void printList(struct Node* n); // function prototype

int main()
{
struct Node *head;
struct Node *middle;
struct Node *last;

// allocate 3 nodes in the heap
head = (struct Node*) malloc(sizeof(struct Node));
middle = (struct Node*) malloc(sizeof(struct Node));
last = (struct Node*) malloc(sizeof(struct Node));

if (head != NULL) {
head->data = 11;
head->data = middle;
}
middle->data = 22;
middle->next = last;
last->data = 12;
last->next = NULL;

printList(head);

_getch();

return 0;
}

void printList(struct Node* n)
{
while (n != NULL)
{
printf(" %d\n", n->data);
n = n->next;
}
}

最佳答案

由于这一行head->data = middle;而出现问题。必须是 head->next = middle;

关于c - 链表打印问题结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58282651/

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