Leetcode: Remove Duplicates from Sorted List
1 min readDec 28, 2016
- Iterate through the list and delete next node if its value matches the current node
2. Delete operation can be simply performed by setting the next pointer to next pointer of next node
Remarks:
- O(n) time, O(1) space
- Note how we can avoid adding a separate condition for empty list.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = Noneclass Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
p = head
while p:
while p.next and p.val == p.next.val:
p.next = p.next.next
p = p.next
return head def deleteDuplicates(self, head): if not head: return None
p = head
while p.next:
if p.val == p.next.val:
p.next = p.next.next
else:
p = p.next
return head