|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在菜单三中添加的那个元素,在菜单四里边删除相同元素后,输出链表但是之前添加的那个元素打印不出来,怎么解决呢
代码:
#include<stdio.h>
#include<stdlib.h>
int Menu();
struct link *Num1();
struct link *Num2();
struct link *Num3();
struct link *Num4();
struct link *Num5();
void Printlink(struct link *link);
struct link
{
int data;
struct link *next;
}*head,*temp,*tail;
void main()
{
int choice;
while(1)
{
choice=Menu();
switch(choice)
{
case 1:Num1();break;
case 2:Num2(head);break;
case 3:Num3(head);break;
case 4:Num4(head);break;
case 5:Num5(head);break;
case 6:
printf("End of program!\n");
exit(0);
default:
printf("Input error!!!\n");
break;
}
}
}
int Menu() //设计菜单
{
int choice;
printf("\n");
printf("1、任务一\n");
printf("2、任务二\n");
printf("3、任务三\n");
printf("4、任务四\n");
printf("5、任务五\n");
printf("6、退出程序\n");
printf("Please input your choice:");
scanf("%d",&choice);
return choice;
}
struct link *Num1()//创建一个仅含头结点的空链表
{
head = (struct link *)malloc(sizeof(struct link));
head->next = NULL;
printf("\n");
if(head == NULL)
{
printf("创建空链表失败\n");
exit(1);
}
else
printf("创建空链表成功\n");
return head;
}
struct link *Num2(struct link *head)//输入数据形成带头结点的单链表,并输出
{
if(head == NULL)
{
printf("链表不存在!\n");
exit(1);
}
else
{
printf("请输入一组数,以(-1)为结束标志:");
while (1)
{
temp = (struct link*)malloc(sizeof(struct link));
if(temp == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
else
{
scanf("%d",&temp->data);
temp->next = NULL;
if (temp->data == -1)
break;
if(head->next == NULL)
head->next = temp;
else
tail->next = temp;
}
tail = temp;
}
tail->next = NULL;
}
Printlink(head);
free(temp);
return head;
}
struct link *Num3(struct link *head)//在链尾插入元素
{
temp = (struct link*)malloc(sizeof(struct link));
if(temp == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
else
{
printf("请输入一个整数:");
scanf("%d",&temp->data);
tail->next = temp;
tail = temp;
tail->next = NULL;
Printlink(head);
}
free(temp);
return head;
}
struct link *Num4(struct link *head)//输入一个整数,删除这个数在第3项完成后的链表中的所有出现,并输出
{
struct link *temp1 = head;
struct link *temp2 = temp1->next;
temp = (struct link*)malloc(sizeof(struct link));
if(temp == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
else
{
printf("请输入一个整数:");
scanf("%d",&temp->data);
temp->next = NULL;
while(temp1->next != NULL)
{
if(temp->data == temp1->next->data)
{
temp1->next = temp2->next;
temp2 = temp2->next;
}
else
{
temp1 = temp1->next;
temp2 = temp2->next;
}
}
}
Printlink(head);
free(temp);
return head;
}
struct link *Num5(struct link *head) //节点逆置
{
struct link *temp3 = head->next;
struct link *tail1;
head->next = NULL;
while(temp3 != NULL)
{
tail1 = temp3;
temp3 = temp3->next;
tail1->next = head->next;
head->next = tail1;
}
Printlink(head);
return head;
}
void Printlink(struct link *link) //输出数据
{
printf("\n");
while(link->next != NULL)
{
printf("%d ",link->next->data);
link = link->next;
}
printf("\n");
} |
|