#include<stdio.h>
#include<malloc.h>
#define NUll 0
#define LEN sizeof(struct node)
struct node
{
int info;
struct node *link;
};
struct linklist
{
struct node *head;
int n;
};
// 单链表输出函数
void print(struct linklist L1);
//单链表查找函数
struct node *Lfind(struct linklist L1,int i);
//单链表的插入函数
int Linsert(struct linklist L1);
//单链表的删除函数
int Ldelete(struct linklist L1);
void main(){
int i;
struct linklist L;
struct node *p,*q;
L.head=(struct node*)malloc(LEN);
p=(struct node*)malloc(LEN);
q=(struct node*)malloc(LEN);
p->info=100;q->info=200;
L.head->link=p; p->link=q; q->link=NULL; L.n=2;
char code;
int flag=1;
while(flag)
{
printf("*********单链表的运算**************\n");
printf("* 主菜单 *\n");
printf("* 1----单链表的插入 *\n");
printf("* 2-----单链表的查找 *\n");
printf("* 3-----单链表的删除 *\n");
printf("* 0-----结 束 *\n");
printf("***********************************\n");
printf("请选择操作:");
scanf("%c",&code);
while(getchar()!='\n');
switch(code){
case '1': L.n=Linsert(L); break;
case '2':
printf("请输入查找链表中第几个结点(0--%d):",L.n);
scanf("%d",&i);
p=Lfind(L,i);
if(p!=NULL) printf("第%d个结点是:%6d\n",i,p->info);
else printf("没有第%d个结点。\n",i); break;
case '3': L.n=Ldelete(L); break;
case '0': flag=0; break;
default: printf("所选择的代码%c是非法代码.\n",code);
}
printf("按任意键,返回\n");
while(getchar()!='\n') ;
}}
// 单链表输出函数
void print(struct linklist L1){
struct node *p1;
p1=L1.head->link;
while(p1!=NUll){
printf("%6d",p1->info);
p1=p1->link;
}
printf("\n");
return;
}
//单链表查找函数
struct node *Lfind(struct linklist L1,int i){
int j;
struct node *p1;
if(i<0) i=0;
if(i>L1.n) i=L1.n;
p1=L1.head;j=0;
while(p1!=NULL&&j<i)
{
p1=p1->link;j=j+1;
}
return p1;
}
//单链表的插入函数
int Linsert(struct linklist L1){
int x,i;
struct node *p1,*q1;
printf("请输入要插入的位置,第几个结点之后(1--%d):",L1.n);
scanf("%d",&i);
getchar();
p1=Lfind(L1,i);
if(p1==NULL){
printf("没有第%d个结点。\n",i);
return L1.n;
}
printf("插入前单链表结点序列如下:\n");
print(L1);
q1=(struct node *)malloc(LEN);
printf("请输入要插入的结点:");
scanf("%d",&q1->info);
q1->link=p1->link; p1->link=q1;L1.n=L1.n+1;
printf("插入后单链表结点序列如下:\n");
print(L1);
return L1.n;
}
//单链表的删除函数
int Ldelete(struct linklist L1){
int i;
struct node *p1,*q1;
printf("请输入要删除第几个结点(1--%d):",L1.n);
scanf("%d",&i);
p1=Lfind(L1,i-1);
if(p1==NULL||p1->link==NULL){
printf("没有第%d个结点。\n",i);
return L1.n;
}
printf("删除前单链表结点序列如下:\n");
print(L1);
q1=p1->link;p1->link=q1->link;L1.n=L1.n-1;
free(q1);
printf("删除后单链表结点序列如下:\n");
print(L1);
return L1.n;
}