【发布时间】:2015-07-14 09:20:55
【问题描述】:
我正在创建一个程序来执行基本的链表操作。现在我已经编写了仅用于在前面插入节点的代码。我运行我的程序来查看它是否工作,但程序在接受节点的输入后终止,然后在切换后打印消息。它甚至不会因为接受我的输入而暂停(就在 main() 结束之前)
这里是代码:
#include <stdio.h>
#include <stdlib.h>
struct linkedlist
{
int num;
struct linkedlist *next;
};
struct linkedlist *head = NULL;
void display();
void insertBeginning()
{
struct linkedlist *obj;
int no;
obj = (struct linkedlist *)malloc(sizeof(struct linkedlist));
if(obj == NULL)
{
printf("\n Overflow ");
}
else
{
printf("\n Enter the number = ");
scanf("%d", &no);
obj->num = no;
if(head == NULL)
{
head = obj;
obj->next = NULL;
}
else
{
obj->next = head;
head = obj;
}
}
}
void display ()
{
struct linkedlist *head2 = head;
while(head2 != NULL)
{
printf("%d ->",head2->num);
head2=head->next;
}
printf("NULL \n");
}
int main()
{
int choice;
char wish;
printf("\n 1. Insert at beginning");
printf("\n 2. Insert at end");
printf("\n 3. Insert in between");
printf("\n 4. Delete from front");
printf("\n 5. Delete from end");
printf("\n 6. Delete from in between");
printf("\n 7. Reverse");
printf("\n 8. Sort ascending");
printf("\n 9. Sort descending");
printf("\n 10.Swap alternate elements");
printf("\n 11.Display\n\n");
do
{
printf("\n Enter the option = ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insertBeginning();
break;
case 2:
// insertEnd();
break;
case 3:
// insertInbetween();
break;
case 4:
// deleteFront();
break;
case 5:
// deleteEnd();
break;
case 6:
// deleteInbetween();
break;
case 7:
// Reverse();
break;
case 8:
// sortAsc();
break;
case 9:
// sortDesc();
break;
case 10:
// swap();
break;
case 11:
display();
break;
default:
printf("\n Wrong choice ");
}
printf("\n Do you wish to continue (y/n) = ");
scanf ("%c",&wish);
}while(wish == 'y' || wish =='Y');
return 0;
}
【问题讨论】:
-
或者您可以在菜单中添加“0. Quit”并跳过“continue (y/n)”
-
在 C 中调用 malloc() 时,不要强制转换返回值。它已经是一个 void* 所以可以分配给任何指针。调用scanf()时,始终检查返回值(不是参数)以确保操作成功
标签: c data-structures malloc singly-linked-list