2013-08-22 51 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的指針,並且你繼續插入相同的節點,並且它最終指向自己。你現在有一個循環列表,這就是爲什麼你有一個無限循環。