Description
You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.
The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x.
- For
n=1,2,3,4, and5, the middle nodes are0,1,1,2, and2, respectively.
Example 1:
Input: head = [1,3,4,7,1,2,6] Output: [1,3,4,1,2,6] Explanation: The above figure represents the given linked list. The indices of the nodes are written below. Since n = 7, node 3 with value 7 is the middle node, which is marked in red. We return the new list after removing this node.
Example 2:
Input: head = [1,2,3,4] Output: [1,2,4] Explanation: The above figure represents the given linked list. For n = 4, node 2 with value 3 is the middle node, which is marked in red.
Example 3:
Input: head = [2,1] Output: [2] Explanation: The above figure represents the given linked list. For n = 2, node 1 with value 1 is the middle node, which is marked in red. Node 0 with value 2 is the only node remaining after removing node 1.
Constraints:
- The number of nodes in the list is in the range
[1, 105]. 1 <= Node.val <= 105
Solutions
This JavaScript function deletes the middle node of a singly-linked list. It first checks if the list is empty or has only one node, in which case it simply returns null because nothing is left after deletion. To find the middle node, it uses a "fast and slow pointer" strategy: a slow pointer moves forward one step at a time, while a fast pointer moves two steps at a time, and a prev pointer tracks the node right before slow. Because the fast pointer travels twice as quickly, by the time it reaches the very end of the list, the slow pointer will be positioned exactly at the middle node. The code then deletes this middle node by linking the prev node directly to the node after the slow node, effectively skipping and removing the middle node before returning the updated list.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteMiddle = function(head) {
if (!head || !head.next) {
return null;
}
let prev = null;
let slow = head;
let fast = head;
while (fast && fast.next) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = slow.next;
return head;
};