#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct node
{
int ans;
struct node *prior,*next;
}Node,*DLinklist;
//初始化头结点
DLinklist init(DLinklist h)
{
h=(Node *)malloc(sizeof(Node));
h->prior=NULL;
h->next=NULL;
return h;
}
//头插法建立双链表
DLinklist creat_head()
{
DLinklist h,p;
int data;
h=init(h);
cout<<"头插法输入数据(遇0结束)"<<endl;
cin>>data;
while(data)
{
p=(Node *)malloc(sizeof(Node));
p->ans=data;
p->next=h->next;
if(h->next!=NULL)
h->next->prior=p;
h->next=p;
p->prior=h;
cin>>data;
}
cout<<"头插法建立双链表成功"<<endl;
return h;
}
//尾插法建立双链表
DLinklist creat_tail()
{
DLinklist h,p,s;
int data;
h=init(h);
p=h;
cout<<"尾插法输入数据(遇0结束)"<<endl;
cin>>data;
while(data)
{
s=(Node *)malloc(sizeof(Node));
s->ans=data;
p->next=s;
s->prior=p;
p=s;
cin>>data;
}
p->next=NULL;
cout<<"尾插法建立双链表成功"<<endl;
return h;
}
//在第n个节点之前插入元素
DLinklist add(DLinklist h)
{
DLinklist p,s;
int data;
p=h;
cout<<"输入要插入元素的位置(在此位置之前插入)"<<endl;
cin>>data;
for(int i=1;i<data;i++)
p=p->next;
cout<<"输入要插入的元素"<<endl;
cin>>data;
s=(Node *)malloc(sizeof(Node));
s->ans=data;
s->next=p->next;
s->prior=p;
p->next->prior=s;
p->next=s;
cout<<"插入成功"<<endl;
return h;
}
//删除指定节点
DLinklist del(DLinklist h)
{
DLinklist p,s;
int data;
cout<<"输入要删除元素的值"<<endl;
cin>>data;
p=h->next;
while(p!=NULL)
{
if(p->ans==data) break;
p=p->next;
}
s=p;
p->prior->next=p->next;
p->next->prior=p->prior;
free(s);
cout<<"删除成功"<<endl;
return h;
}
//遍历双链表
void display(DLinklist h)
{
DLinklist p=(Node *)malloc(sizeof(Node));
p=h->next;
while(p!=NULL)
{
cout<<p->ans<<endl;
p=p->next;
}
}
int main()
{
DLinklist h;
h=creat_head();
display(h);
h=creat_tail();
display(h);
add(h);
display(h);
del(h);
display(h);
return 0;
}