Remove Duplicates from Sorted Linked List - The Coding Shala
Home >> Interview Prep >> Remove Duplicates from Sorted Linked List
Other Posts You May Like
In this post, we will learn how to Remove Duplicates from Sorted Linked List in Java.
Remove Duplicates from Sorted Linked List Problem
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]
Remove Duplicates from Sorted Linked List Java Solution
Approach 1
Iterative method.
Time Complexity: O(n)
Space Complexity: O(1)
Space Complexity: O(1)
Java Program:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode current = head; while(current.next != null) { //check for duplicates if(current.val == current.next.val) { //if duplicate then skip next current.next = current.next.next; } else { current = current.next; } } return head; } }
- Sort a Linked List Using Insertion Sort
- Copy a Linked List with a Random Pointer
- Flatten a Multilevel Doubly Linked List
- Rotate a Linked List
- Merge two Sorted Linked Lists
Comments
Post a Comment