设计链表(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 小时前
LeetCode经典算法面试题 #347:前 K 个高频元素(最小堆、桶排序、快速选择等多种实现方案详解)
算法·leetcode·堆排序·java面试题·桶排序·快速选择·topk
liuyao_xianhui1 小时前
优选算法_分治_快速排序_归并排序_C++
开发语言·数据结构·c++·算法·leetcode·排序算法·动态规划
CryptoPP2 小时前
开发者指南:构建实时期货黄金数据监控系统
大数据·数据结构·笔记·金融·区块链
月落归舟3 小时前
每日算法题 14---14.环形链表
数据结构·算法·链表
光电笑映3 小时前
STL 源码解剖系列:map/set 的底层复用与红黑树封装
c语言·数据结构·c++·算法
沉鱼.443 小时前
滑动窗口问题
数据结构·算法
sheeta19983 小时前
LeetCode 每日一题笔记 日期:2025.03.23 题目:1594.矩阵的最大非负积
笔记·leetcode·矩阵
ysa0510303 小时前
二分+前缀(预处理神力2)
数据结构·c++·笔记·算法
灰色小旋风3 小时前
力扣22 括号生成(C++)
开发语言·数据结构·c++·算法·leetcode
寒月小酒3 小时前
3.23 OJ
数据结构·c++·算法