2020年6月6日 星期六

LeetCode 83. Remove Duplicates from Sorted List [Easy] [C++] 解題筆記

這題給定一個 Linked List ,要求我們刪除裡面重複出現的數字。

EX:
        Input: 1->1->2->3->3
        Ans: 1->2->3
想法:
    這雖然是一題 easy 的題目,但還蠻有意思的很值得練習,雖然要寫出來不難,但要寫得
簡潔也是需要一定程度的練習,尤其對指標的理解需要夠清晰。

完整程式碼:
解法一:
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* cur = head;
        
        while (cur != nullptr && cur->next != nullptr) {
            if (cur->val == cur->next->val) {
                cur->next = cur->next->next;
            }
            else {
                cur = cur->next;
            }
        }
        return head;
    }
};
解法二(pointer of pointer):
// different point of view, change the address that pointer point to 
// instead of change the cur->next
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode** cur = &head;

        while ((*cur) != nullptr && (*cur)->next != nullptr) {
            if ((*cur)->val == (*cur)->next->val) {
                (*cur) = (*cur)->next;
            }
            else {
                cur = &((*cur)->next);
            }
        }
        return head;
    }
};

沒有留言:

張貼留言