Leetcode: Remove Duplicates from Sorted List

Rachit Gupta
1 min readDec 28, 2016

--

  1. 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:

  1. O(n) time, O(1) space
  2. 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 = None
class 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

--

--