以单链表的存储方式存储线性表,包括查找,插入删除,链表显示
include<malloc.h>
include<stdio.h>
include<stdlib.h>
typedef struct linklist
{
int data;
struct linklist *next;
} linklist;
linklist *initlist(linklist *head)
{
linklist *p,*last;
int x;
head=(linklist *)malloc(sizeof(linklist));
head->next=NULL;
last=head;
scanf("%d",&x);
while(x!=0)
{
p=(linklist *)malloc(sizeof(linklist));
p-> data=x;
p->next=last->next;
last->next=p;
last=p;
scanf("%d",&x);
}
return (head);
}
void outputlist(linklist *head)
{
linklist *p;
p=head;
printf("Begin to dump the Linklist...\n");
while(p->next!=NULL)
{
printf("->%d",p->next->data);
p=p->next;
}
printf("\nThe LInkList ended!\n") ;
}
int locatelist(linklist *head,int e)
{
int i=0;
linklist *p;
p=head;
while(p!=NULL)
{
p=p->next;
i=i+1;
if(p->data==e)
return i;
}
return 0;
}
linklist *GetElem_L(linklist *head,int i)
{
linklist *p;
int j=0;
p=head;
while(p && j<i)
{
p=p->next;
++j;
}
if(!p||j>i)
return NULL;
else
return p;
}
void ListInsert_L(linklist *head,int i,int e)
{
linklist *p,*s;
p=GetElem_L(head,i-1);
s=(linklist *)malloc(sizeof(linklist));
s->data=e;
s->next=p->next;
p->next=s;
}
void ListDelete_L(linklist *head,int i,int *e)
{
linklist *p,*q;
p=GetElem_L(head,i-1);
q=p->next;
p->next=q->next;
*e=q->data;
free(q);
}
int main()
{
linklist *head;
printf("请输入线性表元素的值,以0结束:\n");
head=initlist(head);
outputlist(head);
printf("请输入要查找的元素值;\n");
int e,i;
scanf("%d",&e);
i=locatelist(head,e);
if(i)
printf("%d在线性表中的位序是:%d\n",e,i);
else
printf("线性表中不存在元素%d\n",e);
printf("请输入要插入的位置和元素\n");
scanf("%d%d",&i,&e);
ListInsert_L(head,i,e);
outputlist(head);
printf("请输入要删除的第i个位置:");
scanf("%d",&i);
ListDelete_L(head,i,&e);
printf("被删除的元素是:%d\n",e);
outputlist(head);
return 0;
}