//单链表
#define NULL 0
#define OK 1
#define ERROR 0
#include <stdio.h>
#include <stdlib.h>
typedef struct Lnode
{
int data;
struct Lnode *next;
}Lnode;
void InitList_Lk(Lnode *L, int n)
{
Lnode *p;
int i;
L->next=NULL;
for(i=n;i>0;i--)
{
printf("input %d data:/n",i);
p=(Lnode *)malloc(sizeof(Lnode));
scanf("%d",&p->data);
p->next=L->next;
L->next=p;
}
}
void output (Lnode *L)
{
Lnode *p;
for(p=L->next;p;p=p->next) printf("%5d",p->data);
printf("/n");
}
int ListInsert_Lk(Lnode *L,int i,int e)
{
Lnode *p,*s;
int j;
for(p=L,j=0;p&&j<i-1;p=p->next) j++;
if(!p||j>=i) return ERROR;
s=(Lnode *)malloc(sizeof(Lnode));
s->data=e;
s->next=p->next;
p->next=s;
return OK;
}
int ListDelete_L(Lnode *L,int i,int *e)
{
Lnode *p,*s;
int j;
for(p=L,j=0;p->next&&j<i-1;p=p->next) ++j;
if(!(p->next)||(j>=i)) return ERROR;
s=p->next;
p->next=s->next;
*e=s->data; free(s);
return OK;
}
int LocateElem_L(Lnode *L,int e)
{
Lnode *p;
int j;
for(p=L,j=0;p&&p->data!=e;p=p->next) j++;
if (!p) return (ERROR);
if(p->data==e) return j;
else return ERROR;
}
int GetElem_Lk(Lnode *L,int i,int *e)
{
Lnode *p;
int j;
j=1;
p=L->next;
while(p&&(j<i))
{p=p->next;++j;}
if(!p||(j>i)) return ERROR;
*e=p->data;
return OK;
}
void main()
{
Lnode Lb;
int i,d=1,c,x,y;
while(d)
{
printf("input mode:/n");
printf("1:creat 2:output 3:insert 4:delete 5:locate 6:get 7:exit/n");
scanf("%d",&c);
switch(c)
{
case 1:
InitList_Lk(&Lb,3); break;
case 2:
output(&Lb); break;
case 3:
printf("input the inserted num&&data:/n");
scanf("%d%d",&i,&x);
y=ListInsert_Lk(&Lb,i,x);
if(y) printf("that's OK!/n");
else printf("Sorry!/n");
break;
case 4:
printf("input the deleted num:/n");
scanf("%d",&i);
y=ListDelete_L(&Lb,i,&x);
if(y) printf("the data %d deleted./n",x);
else printf("the data not found./n");
break;
case 5:
printf("input the located data:/n");
scanf("%d",&x);
y=LocateElem_L(&Lb,x);
if(y) printf("/nthe data is %dth./n",y);
else printf("/nthe data not found./n");
break;
case 6:
printf("/ninput the num:/n");
scanf("%d",&i);
y=GetElem_Lk(&Lb,i,&x);
if(y) printf("/nthe %dth data is %d./n",i,x);
else printf("/n the data not found./n");
break;
case 7: d=0; break;
}
}
}