2013-08-22 49 views
0

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

调试后,我可以看到我的程序总是进入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(); 

} 
+0

如果您在显示屏内移动'curr',而不是污染全球区域,那么如果您仅在该区​​域内使用它,则会更好。尽量避免使用全局变量。 –

+0

也会检查'display',这样'head'在取消引用前真正指向某个东西。 –

回答

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()看起来没问题。

+0

第一个malloc中的演员是否真的有必要? – AntonioCS

+0

@AntonioCS,这是从原始代码复制。 – Rohan

+0

但是这是C代码,演员是不必要的,对吧? – AntonioCS

0

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

1

您正在设置temp2的下一个开头,然后前往temp2。所以实际上temp2的下一个节点是temp2,这就是为什么你有无限循环。

1

在你的主体中,你有一个指向temp的指针,并且你继续插入相同的节点,并且它最终指向自己。你现在有一个循环列表,这就是为什么你有一个无限循环。