练习双向链表的创建(头插法)、取值、插入、删除完整代码
//双向链表
#include<iostream>
#include<cstdlib>
#define ERROR 0
#define OK 1
typedef int Status;
typedef int Elemtype;
using namespace std;
typedef struct DuNode{
Elemtype data;
struct DuNode *next;
struct DuNode *prior;
}DuNode,*DuLinkList;
DuLinkList p,q;
int j,i,e;
Status GetElem(DuLinkList La,int i,int &e){//取值
for(p=La->next,j=1;p&&j<i;j++){
p=p->next;
}
if(!p||j>i) return ERROR;
e=p->data;
return OK;
}
Status DuListInsert(DuLinkList &La,int i,int e){//把e插到第i个位置 插入
DuLinkList s=(DuLinkList)malloc(sizeof(DuNode));//新节点
s->data = e;
DuLinkList q = La;
for(j=1,p=La->next;j<=i-1&&p;j++){//for(j=1,p=La->next;j<=i-1&&p;j++){
p=p->next;
q=q->next;
}
if(!p||j>i) return ERROR;
s->next = q->next;
s->prior= q;
q->next->prior = s;
q->next= s;
return OK;
}
Status DuLinkDelete(DuLinkList &La,int i,Elemtype &e){//删除
for(j=1,p=La->next;j<i&&p;j++)//定位到位置i
{
p=p->next;
}
if(!p||j>i) return ERROR;
e=p->data;
p->prior->next=p->next;
p->next->prior=p->prior;
free(p);
return OK;
}
Status DuCreatList(DuLinkList &L,int n){//初始化
L=(DuLinkList)malloc(sizeof(DuNode));
L->next=NULL;
for(int i=n;i>0;i--){
DuLinkList s=(DuLinkList)malloc(sizeof(DuNode));
cin>>s->data;
s->next=L->next;
if(L->next != NULL)
L->next->prior = s;
s->prior=L;
L->next=s;
}
return OK;
}
int main(){
DuLinkList p;
DuLinkList L;
cout<<"原链表中数的个数"<<endl;
int n;
cin>>n;
cout<<"原链表中的数"<<endl;
DuCreatList(L,n);
cout<<"现在的链表为:"<<endl;
for(p=L->next;p;p=p->next){
cout<<p->data<<" ";
}
cout<<endl;
cout<<"想得到数的位置:";
cin>>i;
if(GetElem(L,i,e)){
cout<<"第"<<i<<"个数是"<<e<<endl;
}
else cout<<"获取失败"<<endl;
//添加元素
cout<<"添加位置"<<endl;
cin>>i;
cout<<"添加元素的值"<<endl;
cin>>e;
if(DuListInsert(L,i,e)){
cout<<"插入成功 此时的链表为: ";
for(p=L->next;p;p=p->next){
cout<<p->data<<" ";
}
cout<<endl;
}
else cout<<"插入失败"<<endl;
//删除元素
cout<<"删除位置";
cin>>i;
if(DuLinkDelete(L,i,e)){
cout<<"删除成功"<<"删除的值为"<<e<<endl;
cout<<"此时链表为:" <<endl;
for(p=L->next;p;p=p->next){
cout<<p->data<<" ";
}
}
else cout<<"删除失败"<<endl;
}