总时间限制: 100000ms 内存限制: 655360kB
描述
定义有序的双链表类,链表中存储整型数据,创建带头结点的有序双链表,要求包含以下成员函数:
双链表的构造函数(非空的链表,输入数据为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
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;//后
Node* pre;//前
};
class List {
Node* first;
public:
List();
~List();
void Insert(int x);
void Print();
void Delete(int x);
};
List::List()
{
first = new Node;
first->pre = NULL;
first->next = NULL;
}
List::~List()
{
Node* p = NULL;
while (first)
{
p = first->next;
delete first;
first = p;
}
}
void List::Insert(int x)
{
Node* p = NULL;
Node* s = new Node;
s->data = x;
p = first;
while (p->next && x > p->next->data)
{
p = p->next;
}
s->next = p->next;
if (p->next != NULL)
p->next->pre = s;
s->pre = p;
p->next = s;
return;
}
void List::Delete(int x)
{
Node* p=NULL, * q=NULL;
p = first->next;
while (p)
{
if (p->data == x)
{
q = p;
p->pre->next = p->next;
if (p->next != NULL)
p->next->pre = p->pre;
delete q;
}
p = p->next;
}
}
void List::Print()
{
Node* p = first->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
return;
}
int main()
{
int n;
List a;
while (cin >> n && n)
{
a.Insert(n);
}
a.Print();
while (cin >> n && n)
{
a.Insert(n);
}
a.Print();
while (cin >> n && n)
{
a.Delete(n);
}
a.Print();
return 0;
}