Finding middle element in a linked list | Practice | GeeksforGeeks

Given a singly linked list of N nodes.
The task is to find the middle of the linked list. For example, if the linked list is
1-> 2->3->4->5, then the middle node of the list is 3.
If there are two middle nodes(in case, when N is even), print the second middle element.
For example, if the linked list given is 1->2->3->4->5->6, then the middle node of the list is 4.
Example 1:
Input:
LinkedList: 1->2->3->4->5
Output: 3 
Explanation: 
Middle of linked list is 3.

Example 2: 
Input:
LinkedList: 2->4->6->7->5->1
Output: 7 
Explanation: 
Middle of linked list is 7.

Your Task:
The task is to complete the function getMiddle() which takes a head reference as the only argument and should return the data at the middle node of the linked list.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 5000
0
mannukhurana1039710 hours ago
Java
 
int getMiddle(Node head)
    {
        // Time = O(n/2+1);
        // space = O(1)
        if(head==null) return -1;
        if(head.next==null) return head.data;
        
         Node slow=head;
         Node fast=head;
         while(fast.next!=null ){
             slow = slow.next;
             if(fast.next.next==null) return slow.data;
             fast = fast.next.next;
         }
         
         return slow.data;
    }
0
2019sushilkumarkori3 days ago
    int getMiddle(Node *head)
    {
        // Your code here
        int n=0;
        Node* temp=head;
        while(temp!=NULL){
            n++;
            temp=temp->next;
        }
        temp = head;
        int i=0;
        while(temp!=NULL){
            i++;
            if(i == ((n/2)+1)){
                return temp->data;
            }
            temp=temp->next;
        }
    }
0
yw0z81sl8pirjq7u6r2ti6ctdqdgrmfgb0qwqvx06 days ago
Java solution:
 
class Solution{   public static int len(Node node){       int count=0;       while(node!=null){           node=node.next;           count++;       }           return count;       }   int getMiddle(Node head)   {        // Your code here.        int n = len(head);        if(n%2!=0){            for(int i =0;i<((n-1)/2);i++){                                head=head.next;            }            return head.data;        }        else{            for(int i=0;i<n/2;i++){                head=head.next;                            }            return head.data;        }   }}
0
cascadenienuo6 days ago
Idea→ The idea here is to apply the famous fast and slow pointer algorithm. We know that whenever our fast pointer will reach the end, our slow pointer will be pointing to half the distance (i.e. the middle of the linked list), as the speed of the slow pointer is exactly half that of the fast one.
 
class Solution{
   public:
   int getMiddle(Node *head)
   {
       if(head == NULL)return -1;
       Node* fast = head;
       Node* slow = head;
       while(fast->next!=NULL && fast->next->next!=NULL){
           fast = fast->next->next;
           slow = slow->next;
       }
       
//This check is just because it is mentioned in the problem that for even length we need to return the second mid.
       if(fast->next == NULL) 
           return slow->data;
       return slow->next->data;
   }
};
0
cascadenienuo
This comment was deleted.
+1
ritikakumari596736 days ago
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
struct Node{   int data;   struct Node* next;      Node(int x){       data = x;       next = NULL;   }};void printList(Node* node) {    while (node != NULL) {        cout << node->data <<" ";        node = node->next;    }     cout<<"\n";}
// } Driver Code Ends/* Link list Node struct Node {   int data;   Node* next;      Node(int x){       data = x;       next = NULL;   }   }; */class Solution{   public:   /* Should return data of middle node. If linked list is empty, then  -1*/   int getMiddle(Node *head)   {       // Your code here       if(head==NULL)       {           return -1;       }       Node* temp=head;       int count=0;       while(temp!=NULL)       {           temp=temp->next;           count++;       }       int start=0;       Node* t=head;       while(start!=count/2)       {           t=t->next;           start++;       }       return t->data;   }};
// { Driver Code Starts.
int main() {   //code   int t;   cin>>t;   while(t--){       int N;       cin>>N;       int data;       cin>>data;       struct Node *head = new Node(data);       struct Node *tail = head;       for (int i = 0; i < N-1; ++i)       {           cin>>data;           tail->next = new Node(data);           tail = tail->next;       }              Solution ob;       cout << ob.getMiddle(head) << endl;   }   return 0;} // } Driver Code
method-2
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
struct Node{   int data;   struct Node* next;      Node(int x){       data = x;       next = NULL;   }};void printList(Node* node) {    while (node != NULL) {        cout << node->data <<" ";        node = node->next;    }     cout<<"\n";}
// } Driver Code Ends/* Link list Node struct Node {   int data;   Node* next;      Node(int x){       data = x;       next = NULL;   }   }; */class Solution{   public:   /* Should return data of middle node. If linked list is empty, then  -1*/   int getMiddle(Node *head)   {       // Your code here       if(head==NULL)       {           return -1;       }       Node* slow=head;       Node* fast=head;              while(fast!=NULL&&fast->next!=NULL)       {          fast=fast->next->next;           slow=slow->next;                  }              return slow->data;   }};
// { Driver Code Starts.
int main() {   //code   int t;   cin>>t;   while(t--){       int N;       cin>>N;       int data;       cin>>data;       struct Node *head = new Node(data);       struct Node *tail = head;       for (int i = 0; i < N-1; ++i)       {           cin>>data;           tail->next = new Node(data);           tail = tail->next;       }              Solution ob;       cout << ob.getMiddle(head) << endl;   }   return 0;} // } Driver Code Ends
effective way of solving-:
step-1:
take 2 pointer named  slow and fast both pointing on head;
step-2 check it while fast≠ null and fast→next→next ≠ null;
step-3
move slow pointer one step means slow to slow→next
and make fast 2step fast to fast→next→next;
step-4
return slow->data and it will return mid value data
its tc-0(n)
 
0
sudeepgarg6716 days ago
class Solution{   public:   /* Should return data of middle node. If linked list is empty, then  -1*/   int getMiddle(Node *head)   {       Node *temp = head;      int count = 0;      while(temp!=NULL){          count++;          temp = temp->next;      }      int start = 0;      Node *temp2 = head;      while(start!=count/2){          temp2 = temp2->next;          start++;      }      return temp2->data;   }};
0
akaashhardha1 week ago
int getMiddle(Node *head)   {       Node *head_ref = head;       int count = 0;              while(head_ref != NULL){           count++;           head_ref = head_ref->next;       }              if(count % 2 == 0){           int mid = count / 2;            Node *head_ref1 = head;           for(int i = 1 ; i < mid; i++)               head_ref1 = head_ref1->next;           return head_ref1->next->data;       }       else{            int mid = count / 2;            Node *head_ref2 = head;           for(int i = 0 ; i < mid ; i++)               head_ref2 = head_ref2->next;           return head_ref2->data;       }          }};
0
09himanshusah1 week ago
JavaScript Solution
class Solution {
    /* Should return data of middle node. If linked list is empty, then  -1*/
    getMiddle(node)
    {
        //your code here
        let slow = node;
        let fast = node;
        while(fast != null) {
            if(fast.next == null) return slow.data;
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow.data;
    }
}
0
shashankshekhar8891 week ago
def findMid(self, head):
        c=0
        temp=head
        while(temp):
            temp=temp.next
            c+=1
        cur=head
        for i in range(c//2):
            cur=cur.next
        return cur.data
            
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.