实验内容:
用结构体描述一个字符型单链表;创建线性表;在线性表中插入元素,删除元素,显示线性表中所有的元素;用if语句设计一个选择式菜单。
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int elem;
struct node *next;
}NODE,*PNODE;
void create(PNODE &head,int n){
PNODE p;
head = (PNODE)malloc(sizeof(NODE));
head->next = NULL;
for(int i=n;i>0;--i)
{
p = (PNODE)malloc(sizeof(NODE));
scanf("%d",&p->elem);
p->next = head->next;
head->next = p;
}
}
int insert(PNODE head,int i,int elem)
{
PNODE p,s;
int j = 0;
p = head;
while(p && j<i-1){
p = p->next;
++j;
}
if(!p||j>i-1)
{
return 0;
}
s = (PNODE)malloc(sizeof(NODE));
s->elem = elem;
s->next = p->next;
p->next = s;
return 1;
}
int deletelist(PNODE L,int i,int elem)
{
PNODE p,q;
int j = 0;
p = L;
while(p->next && j <i-1){
if(!(p->next)||j>i-1)
return 0;
q = p->next;
p->next= q->next;
elem = q->elem;
free(q);
return 1;
}
}
void show(PNODE L){
PNODE p;
p = L;
printf("显示所有元素:");
while(p->next!=NULL)
{
printf("%d",p->next->elem);
p = p->next;
}
if(L->next == NULL || p == NULL)
{
printf("链表为空!\n");
}
}
void main(){
int choose,i,j=1,n,local,elem;
char x;
PNODE head;
head = NULL;
while(j)
{
printf("\n\t\t------------线性表子系统----------");
printf("\n\t\t*\t 1----建表\t\t\t*");
printf("\n\t\t*\t 2----插入\t\t\t*");
printf("\n\t\t*\t 3----删除\t\t\t*");
printf("\n\t\t*\t 4----展示\t\t\t*");
printf("\n\t\t*\t 0----退出\t\t\t*");
printf("\n\t\t请选择菜单号码\t\t\t*");
scanf("%d",&choose);
printf("\n");
if(choose == 1)
{
printf("输入长度:");
scanf("%d",&n);
create(head,n);
printf("建表成功\n");
}
else if(choose == 2)
{
printf("输入插入位置");
scanf("%d",&local);
printf("输入插入值");
scanf("%d",&elem);
insert(head,local,elem);
}
else if(choose == 3)
{
printf("输入删除的位置");
scanf("%d",&local);
deletelist(head,local,elem);
}
else if(choose == 4)
{
if(head == NULL)
printf("线性表为空");
else
show(head);
}
else if(choose == 0)
{
j = 0;
}
else
printf("输入错误!\n");
}
}
运行结果:![在这里插入图片描述](https://img-blog.csdnimg.cn/20201014165504382.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ1NzI4NDM0,size_16,color_FFFFFF,t_70#pic_center)