代码随想录算法训练营第三天 | 203,707,206

203

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* dummy_node = new ListNode(-1, head);
        ListNode* curr = dummy_node;
        while(curr->next!=nullptr) {
            if (curr->next->val == val) {
                ListNode* tmp = curr->next;
                curr->next = curr->next->next;
                delete tmp;
            }
            else {
                curr = curr->next;
            }
        }
        return dummy_node->next;
    }
};

总结1: 记得c++要手动管理内存

总结2: 设置虚拟头节点要比直接在原链表操作容易且不易出错。

707

class MyLinkedList {

public:
    struct LinkedList {
        int val;
        LinkedList *next;
        LinkedList(int val): val(val), next(nullptr){} 
    };

    MyLinkedList() {
        dummy_node = new LinkedList(0);
        size = 0;
    }
    
    int get(int index) {
        if (index<0 || index>=size) {
            return -1;
        }
        
        LinkedList * curr = dummy_node;
        for (int i=0; inext;
        }
        return curr->val;
    }
    
    void addAtHead(int val) {
        LinkedList * added_node = new LinkedList(val);
        LinkedList * temp = dummy_node->next;
        dummy_node->next = added_node;
        added_node->next = temp;
        size++;
    }
    
    void addAtTail(int val) {
        LinkedList * curr = dummy_node;
        while (curr->next!= nullptr) {
            curr = curr->next;
        }
        LinkedList * added_node = new LinkedList(val);
        curr->next = added_node;
        size++;
    }
    
    void addAtIndex(int index, int val) {
        if (index<0 || index>size) {
            return;
        }
        LinkedList * curr = dummy_node;
        for (int i=0; inext!= nullptr; i++) {
            curr = curr->next;
        }
        LinkedList * added_node = new LinkedList(val);
        LinkedList * temp = curr->next;
        curr->next = added_node;
        added_node->next = temp;
        size++;
    }
    
    void deleteAtIndex(int index) {
        if (index<0 || index>=size) {
            return;
        }
        LinkedList * curr = dummy_node;
        for (int i=0; inext!= nullptr; i++) {
            curr = curr->next;
        }
        LinkedList * delete_node = curr->next;
        curr->next = delete_node->next;
        size--;
    }

private:
    int size;
    LinkedList * dummy_node;


};

总结1: 仍然是虚拟头节点的运用

总结2: 加入运用size,让有index为参数的函数更方便

206

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prev = nullptr;
        ListNode* curr = head;
        while (curr != nullptr) {
            ListNode* next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
};

总结:画图,一步步操作,搞清楚最后return的是什么

你可能感兴趣的:(算法)