2016-03-08 44 views
2

我試圖按照我在鏈接列表中創建每個節點的順序打印出鏈接列表。例如,它應該打印出「0 1 2 3 4」,但我的代碼是錯誤的,不會打印出任何東西。我認爲問題出在我的for循環中。單個鏈接列表按循環順序打印

#include <stdio.h> 
#include <stdlib.h> 
struct node 
{ 
    int data; 
    struct node *next; 
}; 

int main(void) 
{ 
    struct node *head = NULL; 
    struct node *tail = NULL; 
    struct node *current; 
    current = head; 
    int i; 
    for(i = 0; i <= 9; i++) 
    { 
     current = (struct node*)malloc(sizeof(struct node)); 
     current-> data = i; 
     current-> next = tail; 
     tail = current; 
     current = current->next; 
    } 

    current = head; 
    while(current) 
    { 
     printf("i: %d\n", current-> data); 
     current = current->next; 
    } 
} 

回答

0

在構建列表時,您似乎被指針算術絆倒了。試試這個:

int main(void) 
{ 
    struct node *head = NULL; 
    struct node *tail = NULL; 
    struct node *current; 
    int i; 
    for (i=0; i <= 9; i++) 
    { 
     struct node *temp = (struct node*)malloc(sizeof(struct node)); 
     temp-> data = i; 
     temp-> next = NULL; 
     if (head == NULL)   // empty list: assign the head 
     { 
      head = temp; 
      tail = temp; 
      current = head; 
     } 
     else       // non-empty list: add new node 
     { 
      current-> next = temp; 
      tail = temp; 
      current = current->next; 
     } 
    } 

    // reset to head of list and print out all data 
    current = head; 

    while (current) 
    { 
     printf("i: %d\n", current-> data); 
     current = current->next; 
    } 
} 
+0

謝謝!我最終完成了自己,現在瞭解指針的基礎知識。我看起來與你的情況略有不同,因爲我目前正在進行調整,然後我的臨時工被設置爲現在的,但是同樣的基本前提。 –

+0

其實我試過你的代碼,你忘了在else語句的結尾處設置current-> next。你需要這個,因爲否則當你在while循環中打印列表時,它不知道什麼時候停止,並且會做一個奇怪的循環。 –

+0

@DanielMartin實際上,在創建節點時,每個新節點的下一個指針應該設置爲NULL。 –