1. 程式人生 > >82. Remove Duplicates from Sorted List II && i

82. Remove Duplicates from Sorted List II && i

avi mark numbers gin 第一個元素 www node ica element

題目

83. Remove Duplicates from Sorted List

 Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3. 

解析

  • [LeetCode] Remove Duplicates from Sorted List 移除有序鏈表中的重復項
class Solution_83 {
public:
    ListNode *deleteDuplicates(ListNode *head) {

        if (!head||!head->next)
        {
            return head;
        }

        ListNode* cur = head;
        ListNode*pre = NULL;
        while (cur&&cur->next)
        {
            pre = cur;
            cur = cur->next;
            ListNode* temp = pre; //記錄每次重復點的開始位置
while(cur&&pre->val==cur->val) { pre = cur; cur=cur->next; } temp->next = cur; //跳過重復位置 } return head; } };

82. 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. 

解析

  • 由於鏈表開頭可能會有重復項,被刪掉的話頭指針會改變,而最終卻還需要返回鏈表的頭指針。所以需要定義一個新的節點,然後鏈上原鏈表,然後定義一個前驅指針和一個現指針,每當前驅指針指向新建的節點,現指針從下一個位置開始往下遍歷,遇到相同的則繼續往下,直到遇到不同項時,把前驅指針的next指向下面那個不同的元素。如果現指針遍歷的第一個元素就不相同,則把前驅指針向下移一位。

//參考容易理解一些
ListNode *deleteDuplicates(ListNode *head) {
        if (!head || !head->next) return head;
        
        ListNode *start = new ListNode(0);
        start->next = head;
        ListNode *pre = start;
        while (pre->next) {
            ListNode *cur = pre->next;
            while (cur->next && cur->next->val == cur->val) cur = cur->next;
            if (cur != pre->next) pre->next = cur->next;
            else pre = pre->next;
        }
        return start->next;
    }


// 82. Remove Duplicates from Sorted List II
class Solution_82 {
public:
    ListNode* deleteDuplicates(ListNode* head) {

        if (!head||!head->next)
        {
            return head;
        }

        ListNode*newHead = new ListNode(0);
        newHead->next = head;

        ListNode* pre = newHead;
        ListNode* cur = head;
        
        while (cur&&cur->next)
        {
            ListNode* next = cur->next;
        
            if(next->val!=cur->val)
            {
                if (pre->next==cur) //pre->next當前元素開始,cur當前元素結束,cur->next另外不同的元素
                {
                    pre = cur;
                }
                else
                {
                    pre->next = cur->next;
                }
            }
            cur = cur->next;
        }
        if (pre->next!=cur) //這裏是地址比較,若沒有重復元素,則地址相同的
        {
            pre->next = cur->next;
        }
        return newHead->next;
    }
};

題目來源

  • 82. Remove Duplicates from Sorted List II && i

82. Remove Duplicates from Sorted List II && i