[LeetCode] Delete the Middle Node of a Linked List

2095. Delete the Middle Node of a Linked List

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, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if(!head->next) return nullptr;
ListNode *slow = head, *fast = head;
while(fast->next and fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
if(fast->next) {
slow = slow->next;
}
ListNode* runner = head;
while(runner->next != slow) runner = runner->next;
runner->next = slow->next;
return head;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/19/PS/LeetCode/delete-the-middle-node-of-a-linked-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.