1. 程式人生 > >LeetCode83--刪除排序連結串列中的重複元素

LeetCode83--刪除排序連結串列中的重複元素

 

 1 '''
 2 給定一個排序連結串列,刪除所有重複的元素,使得每個元素只出現一次。
 3 示例 1: 輸入: 1->1->2 輸出: 1->2
 4 示例 2: 輸入: 1->1->2->3->3 輸出: 1->2->3
 5 '''
 6 # 關鍵點:排序連結串列
 7 
 8 
 9 class ListNode:
10     def __init__(self, x):
11         self.val = x
12         self.next = None
13 
14 
15 class Solution:
16 def deleteDuplicates(self, head): 17 """ 18 :type head: ListNode 19 :rtype: ListNode 20 """ 21 cur = head 22 while cur is not None and cur.next is not None: 23 if cur.val == cur.next.val: 24 cur.next = cur.next.next 25
else: 26 cur = cur.next 27 return head 28 29 30 if __name__ == '__main__': 31 list1 = [1, 1, 2] 32 l1 = ListNode(1) 33 l1.next = ListNode(1) 34 l1.next.next = ListNode(2) 35 ret = Solution().deleteDuplicates(l1) 36 print(ret)