天天看點

代碼随想錄訓練營第三天| 203.移除連結清單元素,206.反轉連結清單203. 移除連結清單元素206.反轉連結清單

203. 移除連結清單元素

之前全部遷移到vector裡面用數組做的,看卡哥的講解開始學着使用虛拟頭結點

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode* first = new ListNode(0);
        first->next = head;
        ListNode* cur = first;
        while(cur->next != NULL){
            if(cur->next->val==val){
                ListNode* temp = cur->next;//先設定一個臨時節點
                cur->next = cur->next->next;
                delete temp;//需要删除相應節點
            }
           else  cur= cur->next;
        }
        head = first->next;//需要重新定義head,沒有定義的話會報錯
        delete first;//需要删除虛拟頭結點
        return head;
    }
};
           

206.反轉連結清單

看了卡哥的文字版,寫出了雙指針法。

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* prior = head;
        ListNode* rear = NULL;
        ListNode* temp;
        while(prior){
            temp = prior->next;
            prior->next = rear;
            rear = prior;//這兩句話不能寫反,我寫反了之後直接傳回空
            prior = temp;//
        }
        return rear;
    }
};
           

繼續閱讀