[LeetCode] 82. Remove Duplicates from Sorted List II 移除有序链表中的重复项 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.

83. Remove Duplicates from Sorted List 类似,这个题是有重复的元素就全部去掉,只保留独立的元素。

解法:去除重复元素的方法和83类似。但由于第一个元素有可能是重复的,如果删除了就不能往下接了,所以新建一个dummy, dummy.next指向链表。最后返回dummy.next就可以了。

Java:

class Solution {
    public ListNode deleteDuplicates(ListNode head) {  
        if(head == null)  
            return head;  
        ListNode helper = new ListNode(0);  
        helper.next = head;  
        ListNode pre = helper;  
        ListNode cur = head;  
        while(cur!=null)  
        {  
            while(cur.next!=null && pre.next.val==cur.next.val)  
            {  
                cur = cur.next;  
            }  
            if(pre.next==cur)  
            {  
                pre = pre.next;  
            }  
            else  
            {  
                pre.next = cur.next;  
            }  
            cur = cur.next;  
        }  

        return helper.next;  
    }  
}

Python:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
    
    def __repr__(self):
        if self is None:
            return "Nil"
        else:
            return "{} -> {}".format(self.val, repr(self.next))

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(0)
        pre, cur = dummy, head
        while cur:
            if cur.next and cur.next.val == cur.val:
                val = cur.val;
                while cur and cur.val == val:
                    cur = cur.next
                pre.next = cur
            else:
                pre.next = cur
                pre = cur
                cur = cur.next
        return dummy.next

C++:

class Solution {
public:
    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;
    }
};

 

类似题目:

[LeetCode] 83. Remove Duplicates from Sorted List 移除有序链表中的重复项

All LeetCode Questions List 题目汇总

posted @ 2018-03-14 06:01  轻风舞动  阅读(414)  评论(0编辑  收藏  举报