Middle of the Linked List

BRUTE FORCES

class Solution {
public:
    ListNode* middleNode(ListNode* head) { 
    int n = 0;
    ListNode* temp = head;
    while(temp != NULL)
    {
        n++;       //NOT GOOD BECAUSE USE TWO LOOPS
        temp = temp->next;
    }    
    int half = n/2;
    temp = head;
    while(half--)
    {
    temp = temp->next;
    }  
    return temp; }
**** };
**Optimal Solution**
	class Solution {
public:
    ListNode* middleNode(ListNode* head) {
    int n = 0;                                 
    ListNode *fast = head , *slow = head;
    while(fast != NULL && fast->next != NULL)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;      
    }
};
Comments (0)