【发布时间】:2021-07-04 07:34:07
【问题描述】:
我正在编写单链表函数以供练习。在测试不同的函数时,我决定加入一个自动填充功能,而不是使用 Insert Head 或 Insert Tail 函数来制作一个列表来测试 删除和反转功能。我不想重复调用 Insertion 函数,每次都创建一个列表进行测试。
但是,这对我不起作用,它没有按预期工作。它产生了垃圾值并退出了编译。
我无法找到背后的原因。其余代码没有错误,并且按预期运行。
这是我的主要功能:
int main()
{
struct node* head;
int ch,x,pos;
void display(struct node *);
void insert_head(struct node **, int);
void insert_tail(struct node **, int);
void insert_pos(struct node **, int , int);
void delete_first(struct node **);
void delete_last(struct node **p);
void delete_pos(struct node **,int);
void delete_node(struct node **,int);
void reverse(struct node **);
head=NULL;//pointer to the first node
while(1)
{
display(head);
printf("\n1..Insert head\n");
printf("2..Insert tail\n");
printf("3..Display\n");
printf("4..Delete First\n");
printf("5..Delete a node\n");
printf("6..Delete at position\n");
printf("7..Reverse a List\n");
printf("8..Insert at a position\n");
printf("9..Delete last node\n");
printf("10..Autopopulate\n");
printf("11..Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter the number\n");
scanf("%d",&x);
insert_head(&head,x);
break;
case 2:printf("Enter the number\n");
scanf("%d",&x);
insert_tail(&head,x);
break;
case 3:display(head);
break;
case 4:delete_first(&head);
break;
case 5:printf("Enter the value of the node\n");
scanf("%d",&x);
delete_node(&head,x);
break;
case 6:printf("Enter the position");
scanf("%d",&x);
delete_pos(&head,x);
break;
case 7:reverse(&head);
break;
case 8:printf("Enter the value and the position of the node..");
scanf("%d %d",&x,&pos);
insert_pos(&head,x,pos);
break;
case 9:delete_last(&head);
break;
case 10:printf("Entered autopopulate\n");
/* insert_head(&head,5);
insert_head(&head,4); //forced to use this instead of the code below
insert_head(&head,3);
insert_head(&head,2);
insert_head(&head,1); */
//i coded this out hoping for practise with manually making nodes and linking
//them together and to head pointer, however it generated garbage values
//and I'm not able to figure out why
struct node *list1, *list2, *list3, *list4, *list5;
head=list1;
list1=(struct node*)malloc(sizeof(struct node));
list1->data=1;
list1->next=list2;
list2=(struct node*)malloc(sizeof(struct node));
list2->data=2;
list2->next=list3;
list3=(struct node*)malloc(sizeof(struct node));
list3->data=3;
list3->next=list4;
list4=(struct node*)malloc(sizeof(struct node));
list4->data=4;
list4->next=list5;
list5=(struct node*)malloc(sizeof(struct node));
list5->data=5;
list5->next=NULL;
break;
case 11: exit(0);
}
}
}
我希望的输出是:
1->2->3->4->5->NULL
但是,我最终得到了垃圾输出,例如:
17744->
之后程序退出编译而不是重复“请求用户输入”过程。
我希望有一些指针指出我哪里出错了。
说真的,我提前感谢所有抽出时间阅读上述问题的人。谢谢。
【问题讨论】:
-
list1->next=list2;但list2还没有值(请参阅 Yunnosch 的回答)。 -
head=list1; list1=(struct node*)malloc(sizeof(struct node));需要交换这些顺序。也就是说,list1必须是有效的,然后才能使head。
标签: c data-structures