我正在学习链接列表,因此决定在这里做一些练习,我试图显示列表中输入的数据。我还添加了一条评论以表达我的理解
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个数据后,它应该显示我输入的数据。
但它显示“列表为空”
谢谢=)
最佳答案
Node *stnode = (Node *)malloc(sizeof(Node));
这样您就可以隐藏全局变量。这就是为什么您不保留全局变量的任何更改。您所做的只是使用了一个与全局变量 stNode
名称相同的局部变量。
该行应该是
stnode = (Node *)malloc(sizeof(Node));
<子>
不要强制转换 malloc
的返回值。应该是
stnode = malloc(sizeof(Node));
或者更清楚
stnode = malloc(sizeof *stnode);
If you compile this program with
-Wshadow
option then you will get warning regarding this shadowing. Enable all compiler warnings. It helps.
关于c - 链接列表未显示正确的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47614689/