原题
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
解法1
先遍历链表, 将链表的值转为list, 然后将list转化为集合去掉重复值, 再转化为list升序排列, 最后将list转化为链表
Time: O(n) + O(m), n是链表中节点数量, m是集合的长度
Space: O(1)
代码
# 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
"""
l = self.getList(head)
dummy = p = ListNode(0)
for val in l:
p.next = ListNode(val)
p = p.next
return dummy.next
def getList(self, head):
l = []
while head:
l.append(head.val)
head = head.next
return sorted(set(l))
解法2
指针法. 定义cur节点, 如果探测到cur.next节点的值与cur值相同, 则略过cur.next节点
Time: O(n)
Space: O(1)
代码
# 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
"""
cur = head
while cur:
while cur.next and cur.next.val == cur.val:
# skip cur.next
cur.next = cur.next.next
# move to the next node
cur = cur.next
return head