设计链表(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--;
    }
};
相关推荐
杰克尼29 分钟前
BM5 合并k个已排序的链表
数据结构·算法·链表
xiaolang_8616_wjl1 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
hqxstudying2 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
sun0077002 小时前
数据结构——栈的讲解(超详细)
数据结构
凌肖战5 小时前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
黑听人6 小时前
【力扣 简单 C】70. 爬楼梯
c语言·leetcode
ゞ 正在缓冲99%…7 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss7 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
努力写代码的熊大8 小时前
单链表和双向链表
数据结构·链表
Orlando cron9 小时前
数据结构入门:链表
数据结构·算法·链表