【发布时间】:2014-02-19 16:11:55
【问题描述】:
我正在编写 C 代码来实现链表。但是在打印列表的内容时,它只打印最后一个节点的值。我已经调试了很长时间。请帮忙。
#include <stdio.h>
#include <malloc.h>
struct list {
char *name;
char *type;
int occurance;
struct list *prev;
struct list *link;
};
struct list *start=NULL,*ptr,*newnode;
void main() {
int choice = 0;
char name1[10], type1[10];
int occ;
do {
printf("Enter name:");
scanf("%s", name1);
printf("Enter type:");
scanf("%s", type1);
printf("Enter occurance:");
scanf("%d", &occ);
newnode = (struct list *)malloc(sizeof(struct list));
newnode->link = NULL;
newnode->prev = NULL;
newnode->name = name1;
newnode->type = type1;
newnode->occurance = occ;
if(newnode == NULL) {
printf("Memory could not be allocated!");
// exit(0);
}
if(start == NULL) {
start = newnode;
ptr = start;
printf("start is: %s", start->name);
}
else if(start->link == NULL) {
start->link = newnode;
newnode->prev = start;
ptr = newnode;
}
else {
ptr->link = newnode;
newnode->prev = ptr;
ptr = ptr->link;
}
printf("Enter 1 to continue: ");
scanf("%d", &choice);
} while(choice == 1);
// display
ptr = start;
while(ptr != NULL) {
printf("%s ", ptr->name);
printf("%s ", ptr->type);
printf("%d \n", ptr->occurance);
ptr = ptr->link;
}
}
我也尝试过创建 start 和 newnode 局部变量,但它不起作用。
【问题讨论】:
-
Cqnqrd 的回答有。不过,还有一点:1) 您对
newnode==NULL的检查有点晚了,因为您已经取消引用newnode来设置其成员。你不需要start->link==NULL的“else if”;else{}块中的相同代码也适用于这种情况。 -
哦,是的,我现在注意到了,谢谢@dvnrrs
-
将
main的签名改为int main(void)。另请注意,malloc.h不是标准的。请改用stdlib.h。
标签: c data-structures linked-list