我正在学习链表,所以决定在这里做一些练习,我试图显示列表中输入的数据。我也包括我的理解就行了评论链接列表不显示正确的数据
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数据,它应该显示我输入的数据。
但它显示 “列表为空”
谢谢=)
它显示“列表为空”,之后我已经在 – Gaming