Leetcode 83. Remove Duplicates from Sorted List
LeetCode 83: 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.
Input: head = [1, 1, 2]
Output: [1, 2]
Input: head = [1, 1, 2, 3, 3]
Output: [1, 2, 3]
current
, to the head of the linked list.current
pointer.current.next
).current.next
to current.next.next
.current
to the next node.class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
// Start from the head of the list
ListNode current = head;
// Traverse the list
while (current != null && current.next != null) {
// Check if current node is the same as next node
if (current.val == current.next.val) {
// Skip the next node
current.next = current.next.next;
} else {
// Move to the next node
current = current.next;
}
}
return head;
}
}
This solution ensures that all duplicate nodes are removed from the sorted list efficiently, maintaining a linear time complexity and a constant space complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?