定义有序的双链表类,链表中存储整型数据,创建带头结点的有序双链表,要求包含以下成员函数:
双链表的构造函数(非空的链表,输入数据为0,表示输入结束)
插入操作(将一个数据元素插入到有序的双链表中,插入之后链表仍然有序,输入数据为0表示插入操作结束)
按值删除节点(考虑有重复值的情况)
双链表的遍历操作
双链表的析构
输入
输入链表中的元素,根据输入元素,创建有序双链表(非空的链表,输入数据为0,表示输入结束)
输入要插入的值(可以插入多个值,0表示输入结束,)
输入要删除的值(可以删除多个值,0表示结束,)
输出
输出创建的结果
输出插入的结果
输出删除之后的结果
样例输入
1 6 3 7 5 9 0
8 0
2 0
样例输出
1 3 5 6 7 9
1 3 5 6 7 8 9
1 3 5 6 7 8 9
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[1000010],b[100010];
template <class T>
struct node
{
int data;
node<T> *l;
node<T> *r;
};
template <class T>
class lian
{
node<T> *first;
public:
lian();
lian(T a[],int n);
void show();
void cha(T a);
void zhishan(T a);
};
template <class T>
void lian<T>::zhishan(T a)
{
node<T> *p;
p=new node<T>;
p=first->r;
while(p->r!=NULL)
{
if(p->data==a)
{
p->l->r=p->r;
p->r->l=p->l;
delete p;
continue;
}
p=p->r;
}
if(p->data==a)
{
p->l->r=NULL;
delete p;
}
return;
}
template <class T>
lian<T>::lian()
{
first=new node<T>;
first->r=NULL;
first->l=NULL;
}
template <class T>
lian<T>::lian(T a[],int n)
{
first=new node<T>;
first->r=NULL;
first->l=NULL;
node<T> *s,*p;
for(int i=0;i<n;i++)
{
s=new node<T>;
s->r=NULL;
s->l=NULL;
s->data=a[i];
if(first->r==NULL)
{
s->l=first;
first->r=s;
}
else
{
p=first;
while(p->r!=NULL)
{
if(p->r->data>=a[i])
break;
p=p->r;
}
if(p->r!=NULL)
{s->r=p->r;
p->r->l=s;
p->r=s;
s->l=p;}
else
{
p->r=s;
s->l=p;
}
}
}
}
template <class T>
void lian<T>::show()
{
node<T> *p;
p=first->r;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->r;
//t++;
}
cout<<endl;
}
template <class T>
void lian<T>::cha(T a)
{
node<T> *s;
s=new node<T>;
s->data=a;
node<T> *p;
p=first;
while(p->r!=NULL)
{
//if(p->r->data==a)return;
if(p->r->data>=a)
break;
p=p->r;
}
if(p->r!=NULL)
{
s->r=p->r;
p->r->l=s;
s->l=p;
p->r=s;
}
else
{
p->r=s;
s->l=p;
s->r=NULL;
}
}
int main()
{
int t=0;
while(1)
{
int x;
cin>>x;
if(x==0)
break;
a[t]=x;
t++;
}
lian<int> k(a,t);
k.show();
while(1)
{
int x;
cin>>x;
if(x==0)
break;
k.cha(x);
}
k.show();
while(1)
{
int x;
cin>>x;
if(x==0)
break;
k.zhishan(x);
}
k.show();
}