我正在编写C代码来实现链表。但是,在打印列表内容时,它仅打印最后一个节点的值。我一直在调试long.Please help。代码未打印链表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;
}
}
我试图做出开始和newnode
局部变量,以及,但它不能正常工作。
Cqnqrd的回答有它。另一点,虽然:1)你检查'newnode == NULL'有点晚,因为你已经解除引用'newnode'来设置它的成员。并且你不需要“else if”作为'start-> link == NULL';您的'else {}'块中的相同代码也适用于这种情况。 – TypeIA
哦,是的,我现在注意到了,谢谢@dvnrrs – user2538255
将'main'的签名更改为'int main(void)'。还要注意'malloc.h'不是标准的。改为使用'stdlib.h'。 – ajay