#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node *CreateList()//创建一个单链表
{
printf("创建一个长度为n的链表,请输入n:");
int n;
scanf("%d",&n);
node *L;
L=(node *)malloc(sizeof(node));//申请头结点空间
L->next=NULL;//初始化一个空链表
node *p,*r;
r=L;//r始终指向终端结点,开始时指向头结点
int num;//数据
printf("请输入%d个数据:",n);
while(n--)
{
scanf("%d",&num);
p=(node *)malloc(sizeof(node));//申请新的结点
p->data=num;//结点数据域赋值
r->next=p;
r=p;
}
r->next=NULL;
return L;
}
int InsertList(node *L,int i,int e)//插入数据
{
node *p;
p=L;
int j=0;
while(p&&j<i-1)
{
p=p->next;
j++;
}//找到位置前一个节点p
if(!p||j>i-1)
return 0;//插入位置有问题
node *r;//插入的结点为r
r=(node *)malloc(sizeof(node));//开辟新节点
r->data=e;//插入数据
r->next=p->next;//r的指针域指向p的指针域 即p+1的地址
p->next=r;//p的指针域指向r
return 1;
}
int DeleteList(node *L,int i,int *e)//删除数据
{
node *p;
p=L;
int j=0;
while(p->next&&j<i-1)
{
p=p->next;
j++;
}//找到位置前一个节点p
if(!(p->next)||j>i-1)
return 0;//删除位置有问题
node *q;//新指针
q=p->next;//新指针指向p+1的地址
p->next=q->next;//p的指针域指向q+1的地址 即p+2的地址
*e=q->data;
return 1;
}
int SearchList(node *L,int e)//查找数据
{
node *p;
p=L->next;
int i=0;//记录位置
while(p!=NULL)
{
i++;
if(p->data==e)
{
return i;
}
p=p->next;//指向下一个
}
return 0;//找不到返回0
}
void ShowList(node *L)
{
printf("链表中元素为:");
node *r;
r=L->next;
while(r!=NULL)
{
printf("%d ",r->data);
r=r->next;
}
printf("\n");
}
int main()
{
node L;
L=*CreateList();
while(1)
{
printf("1:插入 2:删除 3:查找 0:退出\n");
printf("输入你的选择:");
int xuan;
scanf("%d",&xuan);
int t,shu;
if(xuan==1)
{
printf("请输入数据插入的位置t和数值shu:");
scanf("%d%d",&t,&shu);
printf("%s",InsertList(&L,t,shu)?"插入成功.\n":"插入失败.\n");
printf("插入后:");
ShowList(&L);
}
if(xuan==2)
{
printf("请输入数据删除的位置t :");
scanf("%d",&t);
if(DeleteList(&L,t,&shu))
printf("删除成功.删除的数据是:%d\n",shu);
else
printf("删除失败.位置有误.");
printf("删除后:");
ShowList(&L);
}
if(xuan==3)
{
printf("请输入要查找的数据shu :");
scanf("%d",&shu);
if(SearchList(&L,shu))
printf("查找成功.查找的数据位置是:%d\n",SearchList(&L,shu));
else
printf("查找失败.没有此数据.\n");
}
if(xuan==0)
break;
}
return 0;
}