707.设计链表

之前一直不明白为什么在移除链表元素的题目中,需要将不要的节点手动delete删除。不是说只有创建在堆区的内存需要手动释放嘛?今天三刷完这道设计链表的题目后,突然明白了,链表这种数据结构它的节点都是创建在堆区的,每个节点都是new出来的,所以节点在不用的时候需要手动释放,恍然大悟。。。

之前都是用虚拟头节点做的这道题,这次直接用head进行操作,代码确实复杂了不少,踩了不少坑。注释的那两句代码一定不能忘记,要及时更新head!不然会有各种各样的报错。。。

class MyLinkedList {
    
    
private:
    int size;
    ListNode* head;
public:
    MyLinkedList() {
    
    
        this->size = 0;
        this->head = nullptr;
    }
    
    int get(int index) {
    
    
        if (index < 0 || index >= size) return -1;
        ListNode* cur = head;
        while (index--) cur = cur->next;
        return cur->val;
    }
    
    void addAtHead(int val) {
    
    
        if (size == 0) head = new ListNode(val);
        else {
    
    
            ListNode* tmp = head;
            head = new ListNode(val);
            head->next = tmp;
        }
        ++size;
    }
    
    void addAtTail(int val) {
    
    
        if (size == 0) head = new ListNode(val);
        else {
    
    
            int count = size - 1;
            ListNode* cur = head;
            while (count--) cur = cur->next; 
            cur->next = new ListNode(val);
        }
        ++size;
    }
    
    void addAtIndex(int index, int val) {
    
    
        if (index == size) addAtTail(val);
        else if (index > size) return;
        else if (index < 0) addAtHead(val);
        else {
    
    
            ListNode* dummyHead = new ListNode(0);
            dummyHead->next = head;
            ListNode* cur = dummyHead;
            while (index--) cur = cur->next;
            ListNode* tmp = cur->next;
            ListNode* newNode = new ListNode(val);
            cur->next = newNode;
            newNode->next = tmp;
            head = dummyHead->next; // 这一行不能忘!!!
            delete dummyHead;
            ++size;
        }
    }
    
    void deleteAtIndex(int index) {
    
    
        if (index < 0 || size == 0 || index >= size) return;
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* cur = dummyHead;
        while (index--) cur = cur->next;
        ListNode* tmp = cur->next;
        cur->next = cur->next->next;
        delete tmp;
        head = dummyHead->next; // 这一行不能忘!!!
        delete dummyHead;
        --size;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_54721509/article/details/127905178
今日推荐