有序双链表的实现

总时间限制: 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;
}
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值