[Solved] Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Leetcode solutions MLP Feature Image

Table of Contents

Question

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:

list1
Input: head = [1,1,2]
Output: [1,2]

Example 2:

list2
Input: head = [1,1,2,3,3]
Output: [1,2,3]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

Python Solution

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

class Solution:
    def deleteDuplicates(self, head: ListNode) -> ListNode:
        if head==None:
            return 
        elif head.next==None:
            return head
        else:
            moving = head
            stable = head
            while moving.next!=None:
                if moving.next.val!=moving.val:
                    stable.next = moving.next
                    stable = moving.next
                moving = moving.next

            stable.next=None        
            return head

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top