removeDuplicateNodeFromLinkedList
/**
* Interview Question:
* Given the head of a sorted singly linked list, remove duplicate values in
* place and return the original head.
*
* Input:
* 1 -> 1 -> 3 -> 4 -> 4 -> 4 -> 5 -> 6 -> 6
*
* Output:
* 1 -> 3 -> 4 -> 5 -> 6
*
* Requirements:
* - The linked list is already sorted
* - Remove duplicate nodes, not just duplicate values
* - Keep one copy of each value
* - Modify the list in place
* - Return the head of the cleaned list
*
* Answer:
* Because the list is sorted, duplicate values are adjacent. Walk through the
* list with one pointer. If current.value equals current.next.value, skip the
* next node by setting current.next = current.next.next. Otherwise, move current
* forward.
*
* Complexity:
* O(n) time because each node is visited at most once.
* O(1) space because the list is updated in place.
*
* Node shape used here:
* class LinkedList {
* constructor(value) {
* this.value = value;
* this.next = null;
* }
* }
*
* If your node uses `val` instead of `value`, replace current.value with
* current.val.
*
* @param {{ value: number, next: object | null } | null} head
* @return {{ value: number, next: object | null } | null}
*/
export default function removeDuplicateNodesFromLinkedList(head) {
let current = head;
while (current !== null && current.next !== null) {
if (current.value === current.next.value) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}