设计链表(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--;
    }
};
相关推荐
Doraemomo8 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore9 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
爱跳舞的烤冷面12 小时前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
MC皮蛋侠客13 小时前
Redis 系列(一):全景与最小闭环——从 `SET` 命令到内存数据结构
数据结构·数据库·redis
疯狂打码的少年13 小时前
【数据结构】队列:定义、顺序队列与链式队列
数据结构·笔记
蔬菜_14 小时前
前端转全栈-day5(数组、list、set)
java·前端·数据结构·list
CV-X.WANG16 小时前
从零理解 ORB-SLAM3(二):系统全景、执行上下文与核心数据结构
数据结构
Doraemomo16 小时前
数据结构-二叉树
数据结构
爱跳舞的烤冷面16 小时前
自学嵌入式第20天(数据结构篇——队列)
数据结构
evans在进步16 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先