#include<iostream.h>
typedef char ElemType;
typedef struct DNode
{
ElemType data;
struct DNode *prior;
struct DNode *next;
}linklist;
//1.初始化链表
void chushi(linklist *L)
{
L=new linklist;
L->next=NULL;
}
//2.建立链表
void jianli(linklist *&L,ElemType a[],int n)
{
linklist *s,*r;
L=new linklist;
r=L;
for(int i=0;i<n;i++)
{
s=new linklist;
s->data=a[i];
r->next=s->next;
r->next=s;
s->prior=r;
r=s;
}
r->next=NULL;
}
//3.判断链表是否为空
bool jianyan(linklist *L)
{
return (L->nextNULL);
}
//4.求链表的长度
int changdu(linklist *L)
{
int n=0;
linklist *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return (n);
}
//5.输出链表
void shuchu(linklist *L)
{
linklist *p=L->next;
while(p!=NULL)
{
cout<data<<" ";
p=p->next;
}
cout<<endl;
}
//6.求链表中的某位置的元素值
bool quzhi(linklist *L,int i,ElemType &e)
{
int j=0;
linklist *p=L;
if(i<=0)
return false;
while(j<i&&p!=NULL)
{
j++;
p=p->next;
}
if(pNULL)
return false;
else
{
e=p->data;
return true;
}
}
//7.查找元素的位置
int weizhi(linklist *L,ElemType e)
{
int i=1;
linklist *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
if(pNULL)
return false;
else
return (i);
}
//8.插入元素
bool charu(linklist *&L,int i,ElemType e)
{
int j=0;
linklist *p=L,*s;
if(i<0)
return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(pNULL)
return false;
else
{
s=new linklist;
s->data=e;
s->next=p->next;
if(p->next!=NULL)
p->next->prior=s;
s->prior=p;
p->next=s;
return true;
}
}
//9.删除元素
bool shanchu(linklist *&L,int i,ElemType &e)
{
int j=0;
linklist *p=L,*q;
if(i<=0)
return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(pNULL)
return false;
else
{
q=p->next;
if(qNULL)
return false;
e=q->data;
p->next=q->next;
if(p->next!=NULL)
p->next->prior=p;
delete(q);
return true;
}
}
//10.销毁链表
void xiaohui(linklist *&L)
{
linklist *pre=L,*p=L->next;
while(p!=NULL)
{
delete(pre);
pre=p;
p=p->next;
}
delete§;
}
void main()
{
ElemType b[100];
int c;
cout<<“请输入你要输入元素的个数:”;
cin>>c;cout<<endl;
cout<<“请输入你要输入的元素:”;
for(int i=0;i<c;i++)
cin>>b[i];
linklist *L1;
chushi(L1);
jianli(L1,b,c);
jianyan(L1);
if(jianyan(L1))
cout<<“顺序为空”;
else
cout<<“顺序表不为空”;
cout<<“该顺序表为:”;shuchu(L1);
cout<<“该顺序表长度为:”<<changdu(L1)<<endl;
int a;
ElemType d;
cout<<“请输入你要取的元素的位置:”;
cin>>a;
if(quzhi(L1,a,d))
cout<<“取值成功,第”<<a<<“个位置的值为”<<d<<endl;
else
cout<<“取值失败,你输入的位置不合法”<<endl;
ElemType f;
cout<<"请输入你要查找位置的元素值:";
cin>>f;
if(weizhi(L1,f))
cout<<"位置取值成功,该元素位置为:"<<weizhi(L1,f)<<endl;
else
cout<<"位置取值失败,该元素不存在"<<endl;
int q;
ElemType r;
cout<<"请输入你要插入的位置:";cin>>q;
cout<<"请输入你要插入的元素:";cin>>r;
if(charu(L1,q,r))
{
cout<<"插入成功,此时的顺序表为:";shuchu(L1);
}
else
cout<<"插入失败,你输入的位置不合法"<<endl;
int y;
ElemType u;
cout<<"请输入你要删除的位置:";cin>>y;
cout<<"请输入你要删除的元素:";cin>>u;
if(shanchu(L1,y,u))
{
cout<<"删除成功,此时的顺序表为:";shuchu(L1);
}
else
cout<<"删除失败,你输入的位置不合法";
xiaohui(L1);
}