代码随想录 Leetcode707. 设计链表

发布时间:2024年01月11日

题目:


代码(首刷看解析 2024年1月11日):

class MyLinkedList {
private:
    struct ListNode{
        int val;
        ListNode* next;
        ListNode(int val):val(val),next(nullptr){}
    };
    int size;
    ListNode* dummyHead;
public:

    MyLinkedList() {
        dummyHead = new ListNode(0);
        size = 0;
    }
    
    int get(int index) {
        if( index < 0 || index > size-1 ) return -1;
        ListNode* cur = dummyHead->next;
        while(index--){
            cur = cur->next;
        }
        return cur->val;
    }
    
    void addAtHead(int val) {
        ListNode* newNode = new ListNode(val);
        newNode->next = dummyHead->next;
        dummyHead->next = newNode;
        ++size;
    }
    
    void addAtTail(int val) {
        ListNode* newNode = new ListNode(val);
        ListNode* cur = dummyHead;
        while(cur->next != nullptr){
            cur = cur->next;
        }
        cur->next = newNode;
        size++;
    }
    
    void addAtIndex(int index, int val) {
        if(index > size) return;
        if(index < 0) index = 0;
        ListNode* newNode = new ListNode(val);
        ListNode* cur = dummyHead;
        while(index--){
            cur = cur->next;
        }
        newNode->next = cur->next;
        cur->next = newNode;
        ++size;
    }
    
    void deleteAtIndex(int index) {
        if(index >= size || index < 0) return;
        ListNode* cur = dummyHead;
        while(index--){
            cur=cur->next;
        }
        ListNode* tmp = cur->next;
        cur->next = cur->next->next;
        delete tmp;
        tmp=nullptr;
        --size;
    }
};

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList* obj = new MyLinkedList();
 * int param_1 = obj->get(index);
 * obj->addAtHead(val);
 * obj->addAtTail(val);
 * obj->addAtIndex(index,val);
 * obj->deleteAtIndex(index);
 */

? ? ? ? 写在文后:这道题太考验细节了,我因为各种小错误改了好久不对,最后实在没办法了和参考答案一行一行对才通过,发现是delete里的if中的第一个条件没有写=号,人晕了

文章来源:https://blog.csdn.net/qq_52313711/article/details/135524247
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。