设计链表(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--;
    }
};
相关推荐
Swift社区1 小时前
Swift 解 LeetCode 321:拼接两个数组中的最大数,贪心 + 合并全解析
开发语言·leetcode·swift
无聊的小坏坏2 小时前
力扣 239 题:滑动窗口最大值的两种高效解法
c++·算法·leetcode
黎明smaly2 小时前
【排序】插入排序
c语言·开发语言·数据结构·c++·算法·排序算法
YuTaoShao2 小时前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao2 小时前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
CCF_NOI.3 小时前
(普及−)B3629 吃冰棍——二分/模拟
数据结构·c++·算法
Zedthm3 小时前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱4 小时前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao4 小时前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man5 小时前
LeetCode--42.接雨水
算法·leetcode