代码:
#include<iostream>
#include<malloc.h>
#include<cstdio>
using namespace std;
typedef struct LNode
{
char data;
struct LNode*next;
}LinkNode;
void InitList(LinkNode *& L){
L=(LinkNode*)malloc(sizeof(LinkNode));
L->next=NULL;
}
bool InsertList(LinkNode*& L,int i,char e){
int j=0;
LinkNode *p=L,*s;
if(i<=0) return false;
while (j<i-1&&p!=NULL){
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
s=(LinkNode*)malloc(sizeof(LinkNode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
void DispList (LinkNode *L){
LinkNode *p=L->next;
while(p!=NULL){
printf("%c",p->data);
p=p->next;
}
printf("\n");
}
int LengthList(LinkNode*L){
int n =0;
LinkNode *p=L;
while(p->next!=NULL){
n++;
p=p->next;
}
return n;
}
bool EmptyList(LinkNode* L){
return(L->next==NULL);
}
char GetElem(LinkNode *L,int i){
int j=0;
char e;
LinkNode*p=L;
if(i>0){
while(j<i&&p!=NULL){
j++;
p=p->next;
}
if(p!=NULL)
e=p->data;
}
return e;
}
int LocateElem(LinkNode*&L,char e){
int i=1;
LinkNode *p=L->next;
while(p!=NULL&&p->data!=e){
p=p->next;
i++;
}
if(p==NULL)
return 0;
else
return i;
}
bool DeleteList(LinkNode *&L,int i,char &e){
int j=0;
LinkNode *p=L,*q;
while(j<i-1&&p->next!=NULL){
j++;
p=p->next;
}
if(p==NULL)
return false;
else{
q=p->next;
if(q==NULL)
return false;
e=q->data;
p->next=q->next;
free(q);
return true;
}
}
void DestroyList(LinkNode*& L){
LinkNode *p=L,*s=L->next;
while(s!=NULL){
free(s);
p=s;
s=s->next;
}
free(p);
}
int main (){
LinkNode *L;
char e;
int i;
InitList(L);
InsertList(L,1,'a');
InsertList(L,2,'b');
InsertList(L,3,'c');
InsertList(L,4,'d');
InsertList(L,5,'e');
DispList(L);
printf("%d",LengthList(L));
printf("\n");
if(EmptyList(L)==true)
printf("yes");
else
printf("no");
printf("\n");
printf("%c",GetElem(L,3));
printf("\n");
printf("%d",LocateElem(L, 'a'));
printf("\n");
InsertList(L,4,'f');
DispList(L);
DeleteList(L,3,e);
DispList(L);
DestroyList(L);
}