Skip to main content

Remove Duplicates from Sorted List

Question

Given a sorted linked list, delete all duplicates such that each element appears only once and return the new head of the list.

Example 1
Input: 1 -> 1 -> 2
Output: 1 -> 2

Solution

all//Remove Duplicates from Sorted List.py


# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None

class Solution:
def deleteDuplicates(self, head):
node = head
while node and node.next:
if node.val == node.next.val:
node.next = node.next.next
else:
node = node.next
return head