我正试图打印一个用C创建的链表,但打印顺序错误,我不明白为什么。我正确地分配了指针。有人能帮我吗?这是我的代码:
struct list_el {
int val;
struct list_el * next;
};
typedef struct list_el item;
void main() {
item *curr, *head;
int value;
head = NULL;
scanf("%d", &value);
while (value != 0){
scanf("%d", &value);
curr = (item *)malloc(sizeof(item));
curr->val = value;
curr->next = head;
head = curr;
}
curr = head;
while (curr) {
printf("%dn", curr->val);
curr=curr->next;
}
return 0;
}
scanf("%d", &value);
while (value != 0){
curr = (item *)malloc(sizeof(item));
curr->val = value;
curr->next = head;
head = curr;
scanf("%d", &value);
}
如果您希望列表与输入的顺序相同,则需要追加到列表的末尾(尾部)。
int main() {
item *curr, *head, *tail;
int value;
head = NULL;
scanf("%d", &value);
while (value != 0) {
curr = (item *)malloc(sizeof(item));
curr->val = value;
curr->next = NULL;
if (head == NULL) {
head = tail = curr;
} else {
tail->next = curr;
tail = curr;
}
scanf("%d", &value);
}
...
}
尝试以下操作。在列表中创建一个虚拟节点,以避免显式处理角点情况(空列表等)。
int main() {
item *curr, *head;
int value=-1;
head = (item *)malloc(sizeof(item));
curr = head;
while (value != 0){
scanf("%d", &value);
curr->val = value;
curr->next = (item *)malloc(sizeof(item));
curr = curr->next;
}
curr = head;
while (curr->next) {
printf("%dn", curr->val);
curr=curr->next;
}
return 0;
}
提供
$ ./a.out
1
2
3
4
5
0
1
2
3
4
5
0