美文网首页
【LeetCode-707 | 设计链表】

【LeetCode-707 | 设计链表】

作者: CurryCoder | 来源:发表于2021-12-23 14:43 被阅读0次
题目描述.PNG
#include <iostream>
#include <vector>
#include <stack>
#include <list>
#include <queue>

using namespace std;

class MyLinkedList
{
public:
    struct ListNode
    {
        int val;
        ListNode *next;
        ListNode(int x) : val(x), next(nullptr) {}
    };

    MyLinkedList()
    {
        _size = 0;
        dummy = new ListNode(0);
    }

    int get(int index)
    {

        if (index > (_size - 1) || index < 0)
            return -1;

        ListNode *cur = dummy->next;
        while (index--)
        {
            cur = cur->next;
        }
        return cur->val;
    }

    void addHead(int val)
    {
        ListNode *newNode = new ListNode(val);
        newNode->next = dummy->next;
        dummy->next = newNode;
        _size++;
        return;
    }

    void addTail(int val)
    {
        ListNode *newNode = new ListNode(val);
        ListNode *cur = dummy;
        while (cur->next)
        {
            cur = cur->next;
        }
        cur->next = newNode;
        _size++;
        return;
    }

    void addIndex(int index, int val)
    {
        if (index > _size)
            return;

        ListNode *newNode = new ListNode(val);
        ListNode *cur = dummy;

        while (index--)
        {
            cur = cur->next;
        }

        newNode->next = cur->next;
        cur->next = newNode;
        _size++;
        return;
    }

    void deleteIndex(int index, int val)
    {
        if (index > _size)
            return;

        ListNode *cur = dummy;
        while (index--)
        {
            cur = cur->next;
        }
        ListNode *tmp = cur->next;
        cur->next = cur->next->next;
        delete tmp;
        _size--;
        return;
    }

    void printList()
    {
        ListNode *cur = dummy->next;
        while (cur->next)
        {
            cout << cur->val << " ";
            cur = cur->next;
        }
        cout << endl;
        return;
    }

private:
    int _size;
    ListNode *dummy;
};

相关文章

网友评论

      本文标题:【LeetCode-707 | 设计链表】

      本文链接:https://www.haomeiwen.com/subject/nfbhqrtx.html