Leetcode -- Remove Duplicates from Sorted List II

題目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

分析:將val值重複的node,完全去掉。

思路1:根Remove Duplicates from Sorted List思路一樣,只是在這裏,需要全部去掉。因此需要向前判斷。

代碼1:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(!head) return head;

        ListNode* pre = new ListNode(0);
        ListNode* h = pre;
        ListNode* now;
        ListNode* next;
        now = head;
        while(now)
        {
            next = now->next;
            if(next && now->val == next->val)
            {
                while(next && now->val == next->val)
                {
                    next = next->next;
                }
                pre->next = next;
                now = next;
            }
            else
            {
                pre->next = now;
                pre = pre->next;
                now = next;
            }
        }
        return h->next;
    }
};

【其他思路】:
採用遞歸的方式,每次將滿足條件的node留下,將剩下的作爲新的鏈表,調用函數來判斷。

代碼:【引自:https://leetcode.com/discuss/33666/simple-and-clear-c-recursive-solution

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) return 0;
        if (!head->next) return head;

        int val = head->val;
        ListNode* p = head->next;

        if (p->val != val) {
            head->next = deleteDuplicates(p);
            return head;
        } else {
            while (p && p->val == val) p = p->next;
            return deleteDuplicates(p);
        }
    }
};
發佈了40 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章