5943. Delete the middle node of the linked list

The title

I give you the head node of a linked list, head. Delete the middle node of the list and return the head node of the modified list.

The middle node of the n-length list is the first node ⌊n / 2⌋ (subscripts start from 0), where ⌊x⌋ indicates the largest integer less than or equal to x.

For n = 1, 2, 3, 4, and 5, the subscripts of the intermediate nodes are 0, 1, 1, 2, and 2, respectively.

Example 1

1

Input: head = [1,3,4,7,1,2,6] output: [1,3,4,1,2,6] explanation: the figure above represents the linked list given. The subscripts of nodes are indicated below each node. Since n = 7, node 3 with the value of 7 is the intermediate node, marked in red. The result is a new linked list with the node removed.Copy the code

Their thinking

How fast a pointer

List to find the intermediate value, should first think of fast and slow Pointers;

Here delete the intermediate value, first use the fast and slow pointer to find the intermediate value; Let and then delete the next bit

The following figure

Static figure

code

var deleteMiddle = function(head) {
    let slow = head;
    let fast = head;
    while(fast ! = =null&& fast.next ! = =null){
        slow = slow.next;
        fast = fast.next.next;
    }
    if(slow.next === null) {return head === slow?null:new ListNode(head.val)
    }
    slow.val = slow.next.val;
    slow.next = slow.next.next;
    return head

};
Copy the code