2095. Delete the Middle Node of a Linked List

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
ListNode* deleteMiddle(ListNode* head) {
if(!head->next) return nullptr;
ListNode * pre = head, * slow = head, *fast = head;
while(fast && fast->next){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = slow->next;
return head;
}
};s

analysis

  • time complexity O(n)
  • space complexity O(1)