05:有序的双链表的实现
总时间限制:
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>
#define max 105
using namespace std;
template<typename T>
struct Node {
T data;
Node<T>* prior, * next;
};
template<typename T>
class DoubleLink {
Node<T>* first;
public:
DoubleLink();
// DoubleLink(int c[], int n);
void inset(int x);
void dele(int x);
void println();
};
template<typename T>
DoubleLink<T>::DoubleLink()
{
first = new Node<T>;
first->prior = nullptr;
first->next = nullptr;
int n;
while(cin>>n&&n!=0)
{
inset(n);
}
}
template<typename T>
//DoubleLink<T>::DoubleLink(int a[], int n)
//{
//
// first = new Node<T>;
// first->prior = nullptr;
// first->next = nullptr;
// Node<T>* s;
// s = new Node<T>;
// s->data = a[0];
// s->prior = first;
// s->next = first->next;
// first->next = s;
// for (int i = 1; i < n; i++)
// {
// inset(a[i]);
// }
//}
//template<typename T>
void DoubleLink<T>::dele(int x)
{
Node<T>* p = first->next;
while (p != nullptr) {
if (p->data == x && p->next != nullptr) {
(p->prior)->next = p->next;
(p->next)->prior = p->prior;
}
if (p->data == x && p->next == nullptr) {
(p->prior)->next = p->next;
}
p = p->next;
}
}
template<typename T>
void DoubleLink<T>::inset(int x)
{
Node<T>* p = nullptr;
p = first;
while (p->data < x && p->next != nullptr) {
p = p->next;
}
if (p->data < x) {
Node<T>* s = nullptr;
s = new Node<T>;
s->data = x;
s->next = p->next;
p->next = s;
s->prior = p;
}
if (p->data >= x) {
Node<T>* s = nullptr;
s = new Node<T>;
s->data = x;
s->prior = p->prior;
s->next = (p->prior)->next;
(p->prior)->next = s;
p->prior = s;
}
}
template<typename T>
void DoubleLink<T>::println()
{
Node<T>* p = first->next;
while (p != nullptr)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
int a;
DoubleLink<int>* Lis = new DoubleLink<int>;
Lis->println();
int temp;
while (cin >> temp && temp)
{
Lis->inset(temp);
}
Lis->println();
temp = 1;
while (cin >> temp && temp) {
Lis->dele(temp);
}
Lis->println();
}