Cpp_链表

来源:互联网 发布:wiffi转网络接口 编辑:程序博客网 时间:2024/06/01 08:59

代码如下:
【List.h】

#pragma oncetypedef int DataType;#include <iostream>#include <assert.h>using namespace std;struct SlistNode{    SlistNode* _next;    DataType _data;    SlistNode(DataType x)        :_data(x)        , _next(NULL)    {}};class Slist{    typedef SlistNode Node;public:    Slist() //构造函数        : _head(NULL)        , _tail(NULL)    {}    Slist(const Slist& s);    Slist& operator=(const Slist& s);    ~Slist() //析构函数    {        Node* cur = _head;        while (cur)        {            Node* next = cur->_next;            delete cur;            cur = next;        }        _head = _tail = NULL;    }    Node* BuyNode(DataType x) //创建新节点    {        Node* node = (Node*)malloc(sizeof(Node));        node->_data = x;        node->_next = NULL;        return node;    }    void PushBack(DataType x) //后插    {        if (_head == NULL)        {            _head = _tail = new Node(x);        }        else        {            _tail->_next = new Node(x);            _tail = _tail->_next;        }    }    void PopBack() //后删    {         if (_head == NULL)        {            return;        }        else if (_head == _tail)        {            delete _head;            _head = _tail = NULL;        }        else        {            Node* prev = _head;            while (prev->_next != _tail)            {                prev = prev->_next;            }            delete _tail;            _tail = prev;            _tail->_next = NULL;        }    }     void PushFront(DataType x) //前插    {        if (_head == NULL)        {            _head = _tail = new Node(x);        }        else        {            Node* tmp = new Node(x);            tmp->_next = _head;            _head = tmp;        }    }    void PopFront() //前删    {        if (_head == NULL)        {            return;        }        else if (_head == _tail)        {            delete _head;            _head = _tail = NULL;        }        else        {            Node* del = _head;            _head = _head->_next;            delete del;        }    }    void Print() //打印    {        Node* cur = _head;        while (cur)        {            cout << cur->_data << " ";            cur = cur->_next;        }        cout << endl;    }private:    Node* _head;    Node* _tail;};void TestSlist(){    Slist s;    s.PushBack(1);    s.PushBack(2);    s.PushBack(3);    s.PushBack(4);    s.PushBack(5);    s.Print();}

【test.cpp】

#include "List.h"int main(){    TestSlist();    return 0;}
原创粉丝点击