?代码具体实现:
?
#include <stdlib.h>
#include <stdio.h>
typedef int ElemType;
typedef struct node{
ElemType data;
struct node *next;
}SLink;
void InitList(SLink * &L){
L=(SLink *)malloc(sizeof(SLink));
L->next=NULL;
}
void DestroyElem(SLink * &L){
SLink *pre=L,*p=L->next;
while(p!=NULL){
free(pre);
pre=p;
p=p->next;
}
free(pre);
}
int GetLength(SLink *L){
int i=0;
SLink *p=L->next;
while(p!=NULL){
i++;
p=p->next;
}
return i;
}
int GetElem(SLink *L,int i,ElemType &e){
int j=0;
SLink *p=L;
if(i<1)
return 0;
while(p!=NULL&&j<i){
j++;
p=p->next;
}
if(p==NULL)
return 0;
else{
e=p->data;
return 1;
}
}
int Locate(SLink *L,ElemType e){
SLink *p=L->next;
int j=1;
while(p!=NULL&&p->data!=e){
p=p->next;
j++;
}
if(p==NULL)
return 0;
else
return j;
}
int InsElem(SLink * &L,ElemType x,int i){
SLink *p=L,*s;
int j=0;
if(i<1)
return 0;
while(p!=NULL&&j<i-1){
j++;
p=p->next;
}
if(p==NULL)
return 0;
else{
s=(SLink *)malloc(sizeof(SLink));
s->data=x;
s->next=p->next;
p->next=s;
return 1;
}
}
int DelElem(SLink * &L,int i){
SLink *p=L,*q;
int j=0;
if(i<1)
return 0;
while(p!=NULL&&j<i-1){
j++;
p=p->next;
}
if(p==NULL)
return 0;
else{
q=p->next;
if(q==NULL)
return 0;
else{
p->next=q->next;
free(q);
return 1;
}
}
}
void DispList(SLink *L){
SLink *p=L->next;
while(p!=NULL){
printf("%2d",p->data);
p=p->next;
}
printf("\n");
}
int main(){
int i;
ElemType e;
SLink *L;
InitList(L);
InsElem(L,1,1);
InsElem(L,3,2);
InsElem(L,1,3);
InsElem(L,5,4);
InsElem(L,4,5);
InsElem(L,2,6);
printf("线性表为:");
DispList(L);
printf("长度:%d\n",GetLength(L));
i=3;
GetElem(L,i,e);
printf("第%d个元素:%d\n",i,e);
e=1;
printf("元素%d是第%d个元素\n",e,Locate(L,e));
i=4;
printf("删除第%d个元素\n",i);
DelElem(L,i);
printf("线性表为:");
DispList(L);
DestroyElem(L);
return 0;
}
?