Remove Duplicates
Given the head of a sorted linked list, remove all duplicates such that each element appears only once. Return the modified linked list.
The list is guaranteed to be sorted in non-decreasing order, so duplicates will always appear consecutively. Your goal is to efficiently traverse the linked list and remove all consecutive duplicate nodes.
Example 1
Input:
head = [1, 1, 2]
Output:
[1, 2]
Example 2
Input:
head = [1, 1, 2, 3, 3]
Output:
[1, 2, 3]
Constraints
- The number of nodes in the list is in the range
[0, 300]. - Each node contains an integer value
Node.valwhere-100 <= Node.val <= 100. - The input linked list is sorted in non-decreasing order.
Approach
To solve the problem:
- Traverse the linked list using a pointer.
- Compare each node’s value with the value of its next node.
- If the current node’s value equals the next node’s value, skip the next node by updating the
nextpointer of the current node. - Otherwise, move the pointer to the next node.
This approach ensures a single traversal of the list, giving a time complexity of O(n), where n is the number of nodes in the linked list.
Additional Information
This problem is commonly encountered in scenarios where data needs to be deduplicated while preserving the order. The sorted nature of the input list allows the solution to be implemented in a highly efficient manner without using additional space.
Output will appear here…