lintcode練習-113. 刪除排序連結串列中的重複數字 II
阿新 • • 發佈:2019-02-03
113. 刪除排序連結串列中的重複數字 II
給定一個排序連結串列,刪除所有重複的元素只留下原連結串列中沒有重複的元素。
樣例
給出 1->2->3->3->4->4->5->null
,返回 1->2->5->null
給出 1->1->1->2->3->null
,返回 2->3->null
實現思路:
定義兩個指標,對連結串列進行遍歷,如果兩個指標相等,就刪除所有等於該值的結點。
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: head is the head of the linked list @return: head of the linked list """ def deleteDuplicates(self, head): # write your code here if head is None or head.next is None: return head tmp = dummy = ListNode(0) tmp.next = head pre = head cur = head.next while cur: #如果兩個節點相等,則tmp.next = None if pre.val == cur.val: tmp.next = None flag = pre.val #因為是一位一位的位移,所以判斷pre的值 #如果pre的值等於flag,就忽略 while pre.val == flag: pre = pre.next #當進行到尾結點時cur為none,所以返回 if cur is None: break cur = cur.next else: tmp.next = pre tmp = tmp.next pre = pre.next cur = cur.next return dummy.next