Last updated on October 9th, 2024 at 10:33 pm
Here, We see Remove Duplicates from Sorted List LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
Topics
Linked List
Level of Question
Easy
Remove Duplicates from Sorted List LeetCode Solution
Table of Contents
Problem Statement
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: Input: head = [1,1,2] Output: [1,2] Example 2: Input: head = [1,1,2,3,3] Output: [1,2,3]
1. Remove Duplicates from Sorted List Leetcode Solution C++
class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(!head) return head; ListNode* tmp = head; while(tmp && tmp -> next) { if(tmp -> val == tmp -> next -> val) tmp -> next = tmp -> next -> next; else tmp = tmp -> next; } return head; } };
2. Remove Duplicates from Sorted List Leetcode Solution Java
class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; } }
3. Remove Duplicates from Sorted List Leetcode Solution JavaScript
var deleteDuplicates = function(head) { var current = head; while(current) { if(current.next !== null && current.val == current.next.val) { current.next = current.next.next; } else { current = current.next; } } return head; };
4. Remove Duplicates from Sorted List Leetcode Solution Python
class Solution(object): def deleteDuplicates(self, head): if head == None: return head curr = head while curr.next != None: if curr.val == curr.next.val: tmp = curr.next curr.next = curr.next.next del tmp else: curr = curr.next return head