category-wise-problems

contains category wise problems(data structures, competitive) of popular platforms.

View the Project on GitHub mayankdutta/category-wise-problems

2095. Delete the Middle Node of a Linked List

method 1

ListNode* deleteMiddle(ListNode* head) {
    if (head->next == nullptr) {
        return nullptr;
    }
    
    auto slow = head; 
    auto fast = head; 
    auto prev = head; 
    
    while (fast != nullptr && fast->next != nullptr) {
        prev = slow;
        slow = slow->next;
        fast = fast->next;
        fast = fast->next;
    }
    
    prev->next = slow->next;
    return head;
}

method 2

ListNode* deleteMiddle(ListNode* head) {
    if (head->next == nullptr) {
        return nullptr;
    }
    
    auto slow = head; 
    auto fast = head->next->next; 
    
    while (fast != nullptr && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next;
        fast = fast->next;
    }
    
    slow->next = slow->next->next;
    return head;
}