2095. Delete the Middle Node of a Linked List
Solution
/**
* 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.next) {
head = null;
return head;
}
let f = head;
let s = head;
let prev = null;
while (s.next && s.next.next) {
s = s.next.next;
prev = f;
f = f.next;
}
// Two middle nodes
if (s.next) {
prev = f;
f = f.next;
}
if (prev && prev.next && !prev.next.next) {
prev.next = null;
}
if (prev && prev.next && prev.next.next) {
prev.next = prev.next.next;
}
return head;
};
/**
* 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) {
// Single node list
if (head->next == nullptr) {
delete head;
return nullptr;
}
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = nullptr;
while (fast && fast->next) {
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = slow->next;
return head;
}
};
Complexity
- Time Complexity: O(N), where N is the size of the list.
- Space Complexity: O(1).