Remove Duplicates from Sorted List Visualizer & Step-by-Step Algorithm Solution

Delete all duplicate elements from a sorted singly linked list so each element appears only once.

Category: linked-list | Difficulty: Easy

Tags: Linked List, Two Pointers

Remove Duplicates from Sorted List

head
1
1
2
100%
state
head1
totalNodes3
Initialization
1/11
Explanation

Call deleteDuplicates on sorted list with 3 nodes: [1 -> 1 -> 2 -> null].

Source Code
1function deleteDuplicates(head: ListNode | null): ListNode | null {
2 if (!head || !head.next) return head;
3 let curr = head;
4 while (curr && curr.next) {
5 if (curr.val === curr.next.val) curr.next = curr.next.next;
6 else curr = curr.next;
7 }
8 return head;
9}