Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
思路:维护一前一后两个链表,后面链表先走,有不重复的,就加到前面的链表那里。因为第一个数就可能重复,所以链表要有个表头。
# 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 = ListNode(0)
res.next = head
pre = res
cur = head
while cur:
if cur.next and cur.val == cur.next.val:
while cur and cur.next and cur.val == cur.next.val:
cur = cur.next
pre.next = cur.next
else:
pre = pre.next
cur = cur.next
return res.next