C++ List

#include<iostream>
#include<assert.h>
using namespace std;

typedef int DataType;

struct Listnode
{
    DataType _data;
    Listnode* _next;
    Listnode* _prev;


    Listnode()
        :_data(DataType())
        ,_next(NULL)
        ,_prev(NULL)
    {}
};


class List
{
    typedef Listnode Node;
public:

    List()//构造函数
    {
        _head = new Node;
        _head->_next = _head;
        _head->_prev = _head;
    }

    ~List()//析构函数
    {

        Node *cur = _head->_next;
        while (cur != _head)
        {
            Node *next = cur->_next;
            delete cur;
            cur = next;
        }

        delete _head;
        _head = NULL;

    }


    List(const List& l)//拷贝构造
    {
        _head = new Node;
        _head->_next = _head;
        _head->_prev = _head;

        Node* cur = l._head->_next;
        while (cur != l._head)
        {
            PushBack(cur->_data);
            cur = cur->_next;
        }
    }


    List& operator=(const List& l)//赋值运算符重载
    {
        List tmp(l);
        swap(_head, tmp._head);
        return *this;
    }

    void PushBack(DataType x)//尾插
    {
        Insert(_head, x);
    }


    void PopBack()//尾删
    {
        Erase(_head->_prev);
    }


    void PushFront(DataType x)//头插
    {
        Insert(_head->_next, x);
    }


    void PopFront()//头删
    {
        Erase(_head->_next);
    }


    void Insert(Node* pos, DataType x)//在pos前插入一个节点,值为x
    {
        Node *prev = pos->_prev;
        Node *newnode = new Node;

        newnode->_data = x;
        newnode->_prev = prev;
        prev->_next = newnode;
        newnode->_next = pos;
        pos->_prev = newnode;

    }
    void Erase(Node* pos)//删除pos节点
    {
        assert(pos != _head);
        Node* prev = pos->_prev;
        Node* next = pos->_next;

        delete pos;
        prev->_next = next;
        next->_prev = prev;
    }


    void print()//输出链表
    {
        Node* cur = _head->_next;
        while (cur != _head)
        {
            cout << cur->_data << "  ";
            cur = cur->_next;
        }
        cout << endl;

    }


    size_t size()//求长
    {
        size_t i = 0;
        Node* cur = _head->_next;
        while (cur != _head)
        {
            i++;
            cur = cur->_next;
        }
        return i;
    }
    bool Empty()//判空
    {
        return _head->_next == _head;
    }


private:
    Node* _head;
};

猜你喜欢

转载自blog.csdn.net/Ferlan/article/details/81475140