Remove Duplicates from Sorted List

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.

Solutions

Easy solution, compare current item with next item.

Steps

  1. Iterate list item and compare current item with next item.

  2. If both are same then set current next to current node next to next, else set current node to current node next.

  3. Return head node.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode DeleteDuplicates(ListNode head) {
        
         ListNode p = head;
        if(head == null) return null;
        
        while(p.next != null){
            if(p.val == p.next.val)
                p.next = p.next.next;
            else
                p = p.next;
        }
        return head;
        
    }
}

Time Complexity: O(n)

Auxiliary Space: O(1)

Last updated