1. 程式人生 > >Leetcode 82:刪除排序連結串列中的重複元素 II(最詳細解決方案!!!)

Leetcode 82:刪除排序連結串列中的重複元素 II(最詳細解決方案!!!)

給定一個排序連結串列,刪除所有含有重複數字的節點,只保留原始連結串列中 沒有重複出現 的數字。

示例 1:

輸入: 1->2->3->3->4->4->5
輸出: 1->2->5

示例 2:

輸入: 1->1->1->2->3
輸出: 2->3

解題思路

我們可以很快速的解決這個問題。

 h -> 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5
pre   cur

我們始終要讓precur的前面,通過判斷cur.val == cur.next.val

判斷重複元素是否存在。

 h -> 1 -> 2    3    3    4 -> 4 -> 5
           |              |
           ----------------
          pre            cur

如果存在重複元素的話,我們pre.next=cur.next;cur=cur.next,如果不存在重複元素,我們pre=cur;cur=cur.next,所以這裡我們要通過一個變數標記是否存在重複元素。最後程式碼如下

class Solution:
    def deleteDuplicates
(self, head):
""" :type head: ListNode :rtype: ListNode """ h = ListNode(-1) h.next = head pre = h cur = head while cur != None: duplicate = False while cur.next != None and cur.val == cur.next.val: cur = cur.next duplicate = True
if duplicate == False: pre = cur else: pre.next = cur.next cur = cur.next return h.next

如有問題,希望大家指出!!!