设计链表(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--;
    }
};
相关推荐
Dream it possible!7 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉7 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生7 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴7 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing7 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财7 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程7 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财7 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
liuyuzhongcc10 小时前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
计算机小白一个11 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯