C++实现简单的单链表

浪人 等级 143 0 0

下面实现的是一个简单的单链表

功能不多,学习使用

#pragma once
#include <iostream>
using namespace std;



class ListEx
{
private:
    struct Node
    {
        Node* next;
        int data;
        Node(const Node& node): data(node.data), next(nullptr) {}
        Node(const T& d): data(d), next(nullptr) {}
    };

private:
    Node* head;
    int n; //索引

public:
    ListEx(): head(nullptr), n(0) {}
    Node* getp(int pos)
    {
        if (pos < 0 || pos > n)
        {
            return nullptr;
        }

        if (pos == 0)
        {
            return head;
        }

        Node* p = head;

        for (int i = 1; i < pos; i++)
        {
            p = p->next;
        }

        return p->next;
    }

    void travel()
    {
        Node* p = head;

        if (p == nullptr)
        {
            return;
        }

        p = p->next;

        while (p)
        {
            cout << p->data << "\t" << endl;
            p = p->next;
        }
    }

    void insert(int d, int pos = -1)
    {
        if (head == nullptr)
        {
            head = new Node(0);
            Node* p = new Node(d);
            head->next = p;
            p->next = nullptr;
        }
        //添加到最后
        else if (pos < 0 || pos > n)
        {
            Node* p = getp(n);
            Node* node = new Node(d);
            p->next = node;
            node = nullptr;
        }
        //添加到pos位置
        else
        {
            Node* node = new Node(d);

            Node* p = getp(n - 1);
            Node* q = p->next;
            p->next = node;
            node->next = q;
        }

        ++n;
    }


    //从pos开始查找data 为d的元素,默认从0开始
    int find(int d, int pos = 0)
    {
        Node* p = getp(pos);

        if (p == nullptr)
        {
            return -1;
        }

        while (p)
        {
            if (p->data == d)
            {
                return pos;
            }

            pos++;
            p = p->next;
        }

        return -1;
    }


    //从pos开始删除data为d的元素
    bool erase(int d, int pos = 0)
    {
        int nIndex = find(d, pos);

        if (nIndex == -1)
        {
            return false;
        }

        Node* p = getp(nIndex - 1);
        Node* q = getp(nIndex);

        if (p == nullptr)
        {
            return false;
        }

        p->next = q->next;
        delete q;
        return true;
    }

};
预览图
收藏
评论区