设计链表(leetcode-707)

思路:

(1)获取第n个结点的值

明确链表结点下标从0开始,第n个结点

(2)头部插入结点

注意插入的顺序

(3)尾部插入结点

(4)第n个结点前插入结点

(5)删除第n个结点

cpp 复制代码
class MyLinkedList {
    struct NodeList {
        int val;
        NodeList* next;
        NodeList(int val):val(val), next(nullptr){}
    };

private:
    int size;
    NodeList* dummyhead;

public:

    MyLinkedList() {
        dummyhead = new NodeList(0); 
        size = 0;
    }

    int get(int index) {
        if (index < 0 || index > (size - 1)) {
            return -1;
        }
        NodeList* current = dummyhead->next;
        while(index--){ 
            current = current->next;
        }
        return current->val;
    }

    void addAtHead(int val) {
        NodeList* Newnode = new NodeList(val);
        Newnode->next = dummyhead->next;
        dummyhead->next = Newnode;
        size++;
    }

    void addAtTail(int val) {
        NodeList* Newnode = new NodeList(val);
        NodeList* current = dummyhead;
        while(current->next != NULL){
            current = current->next;
        }
        current->next = Newnode;
        size++;
    }

    void addAtIndex(int index, int val) {
        if (index > size) {
            return ;
        }
        NodeList* Newnode = new NodeList(val);
        NodeList* current = dummyhead;
        while(index--) {
            current = current->next;
        }
        Newnode->next = current->next;
        current->next = Newnode;
        size++;
    }

    void deleteAtIndex(int index) {
        if (index >= size || index < 0) {
            return ;
        }
        NodeList* current = dummyhead;
        while(index--) {
            current = current ->next;
        }
        NodeList* tmp = current->next;
        current->next = current->next->next;
        delete tmp;
        size--;
    }
};
相关推荐
秋难降1 小时前
LRU缓存算法(最近最少使用算法)——工业界缓存淘汰策略的 “默认选择”
数据结构·python·算法
tkevinjd1 小时前
图论\dp 两题
leetcode·动态规划·图论
Jayyih3 小时前
嵌入式系统学习Day19(数据结构)
数据结构·学习
DdduZe4 小时前
8.19作业
数据结构·算法
PyHaVolask4 小时前
链表基本运算详解:查找、插入、删除及特殊链表
数据结构·算法·链表
1白天的黑夜15 小时前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表
上海迪士尼355 小时前
力扣子集问题C++代码
c++·算法·leetcode
花开富贵ii5 小时前
代码随想录算法训练营四十六天|图论part04
java·数据结构·算法·图论
熬了夜的程序员5 小时前
【LeetCode】16. 最接近的三数之和
数据结构·算法·leetcode·职场和发展·深度优先