【LeetCode每天一題】 Remove Duplicates from Sorted List II(移除有序鏈表中重復的節點)
阿新 • • 發佈:2019-05-01
分享 des 一個 lock from 16px jpg 記錄 一道
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
思路
這道題和上一道題目有一點區別的就是移除所有相同的節點,只留下沒有重復的節點。對於這這個題目我們可以使用一個指針指向未重復的節點,然後另外一個指針來跳過重復的節點,一直到最後為止。這裏我們使用了哨兵機制來記錄結果的頭節點。時間復雜度為O(n), 空間復雜度為O(1)。
解決圖示
解決代碼
1 # Definition for singly-linked list. 2 # class ListNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution(object): 8 def deleteDuplicates(self, head): 9 if not head or not head.next: # 為空和只有一個節點直接返回10 return head 11 res, cur = ListNode(0), head # 設置哨兵節點 12 pre = res 13 while pre and cur: # 循環結束條件 14 while cur.next and cur.val == cur.next.val: # 判斷該節點和下一個節點是否相等 15 tem1= cur.val 16 whilecur and cur.val == tem1: # 一直遍歷到下一個和該節點不相等為止。 17 cur = cur.next 18 if not cur: # 是否到為尾節點了 19 pre.next = cur 20 return res.next # 直接返回 21 pre.next = cur # 說明當前節點與下一個節點不相等,移動pre和cur指針為止 22 pre = pre.next 23 cur = cur.next 24 return res.next # 返回節點位置
【LeetCode每天一題】 Remove Duplicates from Sorted List II(移除有序鏈表中重復的節點)