83. Remove Duplicates from Sorted List

Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

Constraints

Approach

Examples

Input: 1 -> 1 -> 2

Output: 1 -> 2

Solutions

/**
 * Time complexity : O(n). Because each node in the list is checked exactly 
 *    once to determine if it is a duplicate or not, the total run time 
 *    is O(n), where n is the number of nodes in the list.
 * Space complexity : O(1). No additional space is used.
 */

/**
 * 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 null;
        ListNode curr = head;
        while(curr.next != null) {
            if(curr.val == curr.next.val) {
                curr.next = curr.next.next;
            } else {
                curr = curr.next;
            }
        }
        return head;
    }
}

Follow up

  • Remove duplicates from an unsorted linked list - GFG

  • Merge two sorted linked list without duplicates - GFG

Last updated

Was this helpful?