2017-07-24 55 views
1

我有兩個功能:顯示循環列表無端環

void display(struct node *start) { 
    struct node *ptr; 

    ptr = start; 

    while (ptr -> next != start) { 
     printf("\t %d", ptr -> data); 
     ptr = ptr -> next; 
    } 

    printf("\t %d", ptr -> data); 
} 

struct node *insert_beg(struct node *start) { 
    struct node *new_node; 

    new_node = (struct node *)malloc(sizeof(struct node)); 
    printf("\n Enter data : "); 
    scanf("%d", &new_node -> data); 

    new_node -> next = start; 
    start = new_node; 

    return start; 
} 

使用insert_beg(start)並試圖顯示使用display(start)此列表之後,我有無限循環。

感謝您的支持。

+4

在功能'insert_beg'變量'start'是*本地*變量。一旦函數返回,您認爲會發生什麼變化?我建議你搜索並閱讀*模擬c *中的引用。 –

+1

@Someprogrammerdude的評論是顯而易見的(而且迄今爲止最明智的),但你怎麼知道*該列表是循環的?它可能有一個起始尾部,就像數字6一樣。你的算法很容易受到這個影響。 – Bathsheba

+0

這是循環鏈表,其中是插入結束函數 – varnit

回答

0

因爲您沒有提供完整的示例,您如何構建循環列表,請讓我假定您使用的功能是錯誤的insert_beg

如果我用你之類的函數如下,沒有死循環:

int main() { 
    struct node* start; 

    start = (struct node*)malloc(sizeof(struct node)); 
    start->data = 1; 
    start->next = start; /* initializing the next pointer to itself */ 

    start->next = insert_beg(start->next); 
    start->next = insert_beg(start->next); 
    start->next = insert_beg(start->next); 

    display(start); 
    return 0; 
} 

我看到一個問題,在您的insert_beg太:

start = new_node; 

如果您打算覆蓋start點這裏那麼您必須將您的功能簽名更改爲以下內容:

struct node *insert_beg(struct node **start); 

然後函數裏面,你可以做到以下幾點:以上

new_node->next = *start; /* access the pointer pointed by start */ 
*start = new_node; /* overwrite where the pointer pointed by start points to*/ 

return *start; /* losts its meaning */ 

的修改,讓你用你的insert_beg功能如下:

insert_beg(&start->next); 
insert_beg(&start->next); 
insert_beg(&start->next); 
+0

非常感謝,非常有幫助, 請問您能解釋爲什麼我們應該使用** start而不是* start? – Fela93

+0

@ Fela93,'struct node * start'意思是指向'struct node''類型的實例的指針,即如果這是一個函數參數,它允許你通過值**傳遞一個指針**,因此改變where該指針指向的內容不會對您傳遞的指針進行任何更改。 'struct node ** start'表示指向指向'struct node' *類型實例的指針的指針*。在這種情況下,間接引用(取消引用)允許您更改傳入指針指向的位置,這將更改您通過地址傳遞的指針。請注意,指針也是一個變量,用於保存目標的地址。 – Akira

+0

所以如果'struct node * start'是一個全局指針結構體,我不需要一個雙精度指針嗎? – Fela93

1

您不在此處創建循環列表。

對於創建循環列表,如果列表中沒有元素,即start爲NULL(列表爲空),則必須處理另一種情況。

製作insert_beg的scanf函數部分後,以下編輯它()函數:

if(start == NULL){  // this is the required condition to be added 
    start = new_node; 
    start->next = start; 
} 
else{ 
    // this code for adding element is to be performed only when list is not empty 
    struct node *tmp = start->next; 
    start->next = new_node; 
    new_node->next = temp; 
} 

我希望這將解決您的問題!

+0

修復是部分的:您需要將最後一個節點指向新的起始節點。 – chqrlie

+1

感謝您的建議!請檢查現在它將工作,因爲編輯後的代碼將在開始指針節點之後添加新節點。 – amol13

+0

它確實創建了一個循環列表,但順序不同。我懷疑'insert_beg'函數應該在**開始節點之後插入**。 – chqrlie