实验项目3 (链表综合应用):
菜单第1项完成:
创建一个仅含头结点的空链表,如果创建成功,输出创建空链表成功,返回头结点的指针,否则输出创建空链表失败,退出程序运行。
菜单第2项完成:
依次输入一组整数,以-1作为结束的标志,创建由这些输入数据所形成的带头结点的单链表,输出链表的数据信息,返回头结点的指针。若输入:45,45, 23,45,54,25, -1。则生成链表:
菜单第3项完成:
输入一个整数。将这个数插入在第2项建立的链表的链尾,并输出整个链表中的数据信息。
菜单第4项完成:
输入一个整数,删除这个数在第3项完成后的链表中的所有出现,并输出删除后链表的数据信息。
菜单第5项完成:
将第4项完成后的链表中的数据逆置,并输出。(备注:由于输出链表中的数据要多次使用,可以编一输出函数,多次调用完成输出)
代码如下:
#include<stdio.h>
#include<stdlib.h>
struct link *build();
struct link *input(struct link *head);
void add(struct link *head);
void det(struct link *head);
void dt(struct link *head);
void print(struct link *head);
struct link
{
int data;
struct link* next;
};
int main()
{
int n;
struct link* head=NULL;
do{
printf("请输入选择的功能:\n");
printf("1:创建一个仅含头节点的空链表\n");
printf("2:向链表中输入数据\n");
printf("3:添加某个数据并输出所有数据\n");
printf("4:删除链表中的某个数据\n");
printf("5:将链表中的数据逆置\n");
printf("6:结束程序\n");
scanf("%d",&n);
switch(n)
{
case 1:
head=build();
printf("\n");
break;
case 2:
head=input(head);
printf("\n");
break;
case 3:
add(head);
print(head);
printf("\n");
break;
case 4:
det(head);
print(head);
printf("\n");
break;
case 5:
dt(head);
print(head);
printf("\n");
break;
case 6:
exit(0);
printf("\n");
break;
}
}while(n!=6);
}
struct link *build()
{
struct link *p,*pr,*head;
int i;
p=(struct link*)malloc(sizeof(struct link));
if(p!=NULL)
{
head=p;
p->next=NULL;
printf("创建成功");
}
else
{
printf("创建失败");
exit(0);
}
return head;
}
struct link *input(struct link *head)
{
int x;
struct link *p,*pr=head;
printf("请依次输入数据,以‘-1’作为结束标志:\n");
scanf("%d",&x);
while(x!=-1)
{
p=(struct link*)malloc(sizeof(struct link));
if(p!=NULL)
{
p->data=x;
pr->next=p;
pr=p;
scanf("%d",&x);
}
else
{
printf("错误");
exit(0);
}
}
p->next=NULL;
return head;
}
void add(struct link *head)
{
int i;
struct link *p=head,*pr;
while(p->next!=NULL)
{
p=p->next;
}
pr=(struct link*)malloc(sizeof(struct link));
if(pr!=NULL)
{
p->next=pr;
printf("请输入添加的数据:");
scanf("%d",&i);
pr->data=i;
pr->next=NULL;
}
else
{
printf("错误");
exit(0);
}
}
void print(struct link *head)
{
struct link *pt;
pt=head;
pt=pt->next;
while(pt!=NULL)
{
printf("%5d",pt->data);
pt=pt->next;
}
}
void det(struct link *head)
{
int x,i=0;
struct link *pt=head,*pr;
pr=pt;
pt=pt->next;
printf("请输入要删除的数据:");
scanf("%d",&x);
while(pt!=NULL)
{
if(pt->data==x)
{
pr->next=pt->next;
free(pt);
pt=pr->next;
}
else
{
pr=pt;
pt=pt->next;
}
}
}
void dt(struct link *head)
{
if(head==NULL||head->next==NULL)
return;
struct link *pr,*pa=NULL,*pt=NULL;
pr=head->next;
while(pr->next!=NULL)
{
pt=pr->next;
pr->next=pa;
pa=pr;
pr=pt;
}
pr->next=pa;
head->next=pr;
}