链表打印问题结构

时间:2019-10-08 08:24:24

标签: c

我开发了一个链表,但是当我将“ 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;
    }
}

1 个答案:

答案 0 :(得分:1)

此行head->data = middle;引起的问题。必须为head->next = middle;

相关问题