链表打印问题结构



我开发了一个链表,但是当我传递"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(" %dn", n->data);
n = n->next;
}
}

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

最新更新