75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

876. Middle of the Linked List

O(N) Time solution

Code

class Solution{
public:
    ListNode *middleNode(ListNode *head){
        int n = 0;
        ListNode *temp = head;
        while (temp != NULL){
            n++;
            temp = temp->next;
        }
        int mid = n / 2;

        temp = head;
        while (mid--){
            temp = temp->next;
        }

        return temp;
    }
};

O(N) Slow and Fast pointer

Code

class Solution{
public:
    ListNode *middleNode(ListNode *head){
        int n = 0;
        ListNode *slow = head, *fast = head;
        while (fast != NULL && fast->next != NULL){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};