原題
給定一個排序鏈表,刪除所有重復的元素每個元素只留下一個。
樣例
給出 1->1->2->null,返回 1->2->null
給出 1->1->2->3->3->null,返回 1->2->3->null
解題思路
- 基礎鏈表操作,遍歷一遍去重
完整代碼
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
res = head
if not head:
return res
while head.next != None:
if head.val == head.next.val:
head.next = head.next.next
else:
head = head.next
return res