Cpp_链表

代码如下:
【List.h】

#pragma once

typedef 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值