调试C链接列表程序陷入无限循环

时间:2013-08-22 12:42:53

标签: c linked-list

所以这是一个非常简单的程序来创建和显示链表。在这里,我陷入了显示循环,我在屏幕上看到无限的“2-> 2-> 2-> ...”。

调试之后,我可以看到我的程序总是进入if insertNode()语句,而它应该只在那里进行,即初始化链表时。

    #include <stdio.h>
#include <stdlib.h>

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

struct node * head = NULL;
struct node * curr = NULL;

void insertNode(struct node * temp2) {
    if (head == NULL) {
        head = temp2;
        head->next = NULL;
    }
    else {
        temp2->next = head;
        head = temp2;
    }
}

void display() {
    curr = head;
    while (curr->next != NULL)
    {   
        printf("%d->",curr->data);
        curr = curr->next;
    }
}

void main() {
    struct node * temp = (struct node *) malloc (sizeof(struct node));
    temp->data = 5;
    insertNode(temp);
    temp->data = 6;
    insertNode(temp);
    temp->data = 1;
    insertNode(temp);
    temp->data = 2;
    insertNode(temp);
    display();

}

4 个答案:

答案 0 :(得分:2)

在将每个数据插入链接列表时,应为每个数据分配和创建新节点。

void main() {
    struct node * temp = (struct node *) malloc (sizeof(struct node));
    temp->data = 5;
    insertNode(temp);

    temp = malloc (sizeof(struct node));
    temp->data = 6;
    insertNode(temp);

    temp = malloc (sizeof(struct node));
    temp->data = 1;
    insertNode(temp);

    temp = malloc (sizeof(struct node));
    temp->data = 2;
    insertNode(temp);
    display();

}

当您使用相同的节点添加为多个节点时,它会生成循环列表。

您的insertNode()看起来不错。

答案 1 :(得分:1)

您要设置temp2的下一个,然后前往temp2。所以实际上temp2的下一个节点是temp2,这就是你有无限循环的原因。

答案 2 :(得分:1)

在你的main中你有一个指向temp的指针,你继续插入同一个节点,它最终指向自己。您现在有一个循环列表,这就是您有无限循环的原因。

答案 3 :(得分:0)

您将获得无限循环,因为您只有一个节点。执行temp->data = 5;然后temp->data = 6;不会创建新节点。因此,当您再次将同一节点添加到列表中时,节点中的next指针指向自身。因此,显示中的while循环永远不会终止,因为next节点始终是当前节点。