2017-12-03 121 views
0

我正在學習鏈表,所以決定在這裏做一些練習,我試圖顯示列表中輸入的數據。我也包括我的理解就行了評論鏈接列表不顯示正確的數據

typedef struct node { 
    int num; 
    struct node *nextptr; 
}Node; 

Node *stnode; 
void createNodeList(int n); 
void displayList(); 

這是我創建的節點

void createNodeList(int n) { 
    Node *tmp; 
    int num = 1; 

    //allocate memory address to stnode 
    Node *stnode = (Node *)malloc(sizeof(Node)); 

    if (stnode == NULL) { 
     printf("Memory error"); 
    } 
    else { 
     printf("Input data for node 1:"); 
     scanf("%d", &num); 

     //declare the stnode num field in struct as user input 
     stnode->num = num; 
     //declare the stnode address of the next node NULL (to be the last node) 
     stnode->nextptr = NULL; 
     //define the node name as tmp 
     tmp = stnode; 

     for (int i = 2; i <= n; i++) { 
      //allocate node to fnNode 
      Node *fnNode = (Node *)malloc(sizeof(Node)); 
      if (fnNode == NULL) { 
       printf("Memory can not be allocated"); 
       break; 
      } 
      else { 
       printf("Input data for node %d: ", i); 
       scanf("%d", &num); 

       //declare the node name fnNode num to store user input 
       fnNode->num = num; 
       //link the fnNode of nextptr to address null 
       fnNode->nextptr = NULL; 
       //link tmp node to fnNode 
       tmp->nextptr = fnNode; 

       tmp = tmp->nextptr; 
      } 
     } 
    } 
} 

這是爲了顯示他們

void displayList() { 
    Node *tmp; 
    if (stnode == NULL) { 
     printf("List is empty"); 
    } 
    else { 
     tmp = stnode; 
     while (tmp != NULL) { 
      printf("Data = %d\n", tmp->num); 
      tmp = tmp->nextptr; 
     } 
    } 
} 

後,我已經輸入3數據,它應該顯示我輸入的數據。

但它顯示 「列表爲空」

謝謝=)

+0

它顯示「列表爲空」,之後我已經在 – Gaming

回答

0
Node *stnode = (Node *)malloc(sizeof(Node)); 

通過這一點,你是陰影的全局變量。這就是爲什麼你不保留全局變量的變化。您所做的全部使用與全局變量stNode具有相同名稱的本地變量。

這行應該是

stnode = (Node *)malloc(sizeof(Node)); 

不要投malloc返回值。它應該是

stnode = malloc(sizeof(Node)); 

甚至更​​清楚

stnode = malloc(sizeof *stnode); 

如果使用-Wshadow選項編譯這個程序,那麼你將得到 對此陰影警告。啓用所有編譯器警告。它 有幫助。

+0

裏面輸入了數據哇。非常感謝。所以我的錯誤是宣佈兩個stnode? 也是我的理解通過評論做得對嗎? – Gaming

+0

@遊戲:是的。您已經聲明瞭一個與全局作用域中名稱相同的變量。這就是爲什麼本地範圍被用來影響全球範圍的原因。 – coderredoc