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