Traverse the origin linked list and count the visited numbers. Then append distinct number to the output linked list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode(0)
p1 = dummy
p2 = head
count = 1
while p2 and p2.next:
if p2.val == p2.next.val:
count += 1
p2 = p2.next
else:
if count == 1:
p1.next = p2
p1 = p1.next
count = 1
p2 = p2.next
if p2 and count == 1:
p1.next = p2
p1 = p1.next
# end the output linked list
p1.next = None
return dummy.next
A Sliding-window solution:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
p = head
q = head
dummy = ListNode()
n = dummy
while p:
while q and p.val == q.val:
q = q.next
if p.next == q:
n.next = p
n = n.next
p = q
# end the new list
n.next = None
return dummy.next
No comments:
Post a Comment