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.

Input: head = [1, 1, 2]
Output: [1, 2]
Input: head = [1, 1, 2, 3, 3]
Output: [1, 2, 3]

Since the list is sorted, all duplicate values are adjacent. We can traverse the list once, and whenever the current node's value equals the next node's value, we skip the next node by updating the next pointer.

class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class RemoveDuplicatesFromSortedList { public ListNode deleteDuplicates(ListNode head) { ListNode curr = head; while (curr != null && curr.next != null) { if (curr.val == curr.next.val) { // Skip the duplicate next node curr.next = curr.next.next; } else { // Move to next distinct node curr = curr.next; } } return head; } }
Complexity Analysis:

Time complexity: O(n) where n is the length of the list. Each node is visited at most once.
Space complexity: O(1) as only a single pointer is used for traversal.