2017-12-03 118 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