#include <iostream>
//#include <sdlib.h>
#include <malloc.h>
#include <list>
#include <vector>
#define MaxSize 50
using namespace std;
typedef char ElemType;
typedef struct LNone{
ElemType data;
struct LNone *next;
}LinkNone;
void InitList(LinkNone *&L)
{
L=(LinkNone *)malloc(sizeof(LinkNone));
L->next=NULL;
}//初始化单链表
void DestroyList(LinkNone *&L)
{
LinkNone *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=pre->next;
}
free(pre);
}
bool ListEmpty(LinkNone *L)
{
return (L->next==NULL);
}
int ListLength(LinkNone *L)
{
int n=0;
LinkNone *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return(n);
}
void DispList(LinkNone *L)
{
LinkNone *p=L->next;
while(p!=NULL)
{
printf("%c ",p->data);
p=p->next;
}
printf("\n");
}
bool GetElem(LinkNone *L,int i,ElemType &e)
{
int j=0;
LinkNone *p=L;
if(i<=0) return false;
while(j<i&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
{
return false;
}
else
{
e=p->data;
return true;
}
}
int LocataElem1(LinkNone *L,ElemType e)
{
int i=1;
LinkNone *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(p==NULL)
return (0);
else
return (i);
}
int LocataElem2(LinkNone *L,ElemType e)
{
int i=1;
LinkNone *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(p==NULL)
return (0);
else
return (i);
}
bool ListInsert(LinkNone *&L,int i,ElemType e)
{
int j=0;
LinkNone *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=(LinkNone *)malloc(sizeof(LinkNone));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
bool ListDelete(LinkNone *&L,int i,ElemType e)
{
int j=0;
LinkNone *p=L,*q;
if(i<=0) return false;
while(j<i-1&&p!=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;
}
}
int main()
{
LinkNone *L;
ElemType e;
InitList(L);
ListInsert(L,1,'a');
ListInsert(L,2,'b');
ListInsert(L,3,'c');
ListInsert(L,4,'d');
ListInsert(L,5,'e');
DispList(L);
printf("%d\n",ListLength(L));
if(!ListEmpty(L))
printf("此链表不为空\n");
else
printf("此链表为空\n");
if(GetElem(L,3,e))
printf("%c\n",e);
else
printf("不存在此值\n");
printf("%d\n",LocataElem1(L,'a'));
ListInsert(L,4,'f');
DispList(L);
ListDelete(L,3,e);//无序
DispList(L);
DestroyList(L);
//DispList(L);
//return 0;
}
输出数据: