LintCode Python 簡單級題目 112.刪除鏈表中的重復元素
阿新 • • 發佈:2017-06-07
末尾 元素 簡單 remove def toggle strong 留下 logs
題目描述:
給定一個排序鏈表,刪除所有重復的元素每個元素只留下一個。
您在真實的面試中是否遇到過這個題? Yes 樣例給出 1->1->2->null
,返回 1->2->null
給出 1->1->2->3->3->null
,返回 1->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: A ListNode @return: A ListNode """ def deleteDuplicates(self, head): # write your code here if head is None: return None pre = head cur = pre fol = pre.next while fol.next is not None: # 一直找到第一個與pre值不等的fol,刪除中間所有重復元素 if pre.val == fol.val: fol = fol.next else: pre.next = fol pre = fol fol = pre.next # 檢測末尾是否相等 if pre.val == fol.val: pre.next = fol.next else: pre.next = fol return cur
LintCode Python 簡單級題目 112.刪除鏈表中的重復元素