Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Find Middle of the Linked List
Next article icon

Find Middle of the Linked List

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a singly linked list, the task is to find the middle of the linked list. If the number of nodes are even, then there would be two middle nodes, so return the second middle node.

Example:

Input: linked list: 1->2->3->4->5
Output: 3 
Explanation: There are 5 nodes in the linked list and there is one middle node whose value is 3.

Input: linked list = 10 -> 20 -> 30 -> 40 -> 50 -> 60
Output: 40
Explanation: There are 6 nodes in the linked list, so we have two middle nodes: 30 and 40, but we will return the second middle node which is 40.

Middle-of-a-Linked-List4

Table of Content

  • [Naive Approach] By Counting Nodes - O(n) time and O(1) space
  • [Expected Approach] By Tortoise and Hare Algorithm - O(n) time and O(1) space

[Naive Approach] By Counting Nodes - O(n) time and O(1) space:

The idea is to traversing the entire linked list once to count the total number of nodes. After determining the total count, traverse the list again and stop at the (count/2)th node to return its value. This method requires two passes through the linked list to find the middle element.

C++
// C++ program to illustrate how to find the middle element // by counting the number of nodes #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node* next;        Node(int x) {         this->data = x;         this->next = nullptr;     } };  // Helper function to find length of linked list int getLength(Node* head) {      // Variable to store length     int length = 0;      // Traverse the entire linked list and increment length by     // 1 for each node     while (head) {         length++;         head = head->next;     }      // Return the number of nodes in the linked list     return length; }  // Function to find the middle element of the linked list int getMiddle(Node* head) {      // Finding length of the linked list     int length = getLength(head);      // traverse till we reached half of length     int mid_index = length / 2;     while (mid_index--) {         head = head->next;     }      // Head now will be pointing to the middle element     return head->data; }  int main() {      // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60      Node* head = new Node(10);     head->next = new Node(20);     head->next->next = new Node(30);     head->next->next->next = new Node(40);     head->next->next->next->next = new Node(50);     head->next->next->next->next->next = new Node(60);      cout << getMiddle(head);      return 0; } 
C
// C program to illustrate how to find the middle element // by counting the number of nodes #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* next; };  // Helper function to find length of linked list int getLength(struct Node* head) {      // Variable to store length     int length = 0;      // Traverse the entire linked list and increment length     // by 1 for each node     while (head) {         length++;         head = head->next;     }      // Return the number of nodes in the linked list     return length; }  // Function to find the middle element of the linked list int getMiddle(struct Node* head) {      // Finding length of the linked list     int length = getLength(head);      // Traverse till we reach half of the length     int mid_index = length / 2;     while (mid_index--) {         head = head->next;     }      // Head now will be pointing to the middle element     return head->data; }  struct Node* createNode(int x) {     struct Node* newNode         = (struct Node*)malloc(sizeof(struct Node));     newNode->data = x;     newNode->next = NULL;     return newNode; }  int main() {      // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60      struct Node* head = createNode(10);     head->next = createNode(20);     head->next->next = createNode(30);     head->next->next->next = createNode(40);     head->next->next->next->next = createNode(50);     head->next->next->next->next->next = createNode(60);      printf("%d\n", getMiddle(head));      return 0; } 
Java
// Java program to illustrate how to find the middle element // by counting the number of nodes  // A singly linked list node class Node {     int data;     Node next;      // Constructor to initialize a new node with data     Node(int x) {         this.data = x;         this.next = null;     } }  class GfG {      // Helper function to find length of linked list     static int getLength(Node head) {          // Variable to store length         int length = 0;          // Traverse the entire linked list and increment         // length by 1 for each node         while (head != null) {             length++;             head = head.next;         }          // Return the number of nodes in the linked list         return length;     }      // Function to get the middle value of the linked list     static int getMiddle(Node head) {                // Finding the length of the list         int length = getLength(head);          // traverse till we reached half of length         int mid_index = length / 2;         while (mid_index > 0) {             head = head.next;             mid_index--;         }         // temp will be storing middle element         return head.data;     }      public static void main(String[] args) {          // Create a hard-coded linked list:         // 10 -> 20 -> 30 -> 40 -> 50 -> 60          Node head = new Node(10);         head.next = new Node(20);         head.next.next = new Node(30);         head.next.next.next = new Node(40);         head.next.next.next.next = new Node(50);         head.next.next.next.next.next = new Node(60);          System.out.println(getMiddle(head));     } } 
Python
# Java program to illustrate how to find the middle element # by counting the number of nodes  class Node:     def __init__(self, x):         self.data = x         self.next = None  # Helper function to find length of linked list def getLength(head):      # Variable to store length     length = 0      # Traverse the entire linked list and increment length     # by 1 for each node     while head:         length += 1         head = head.next      # Return the number of nodes in the linked list     return length  # Function to find the middle element of the linked list def getMiddle(head):      # Finding length of the linked list     length = getLength(head)      # Traverse till we reach half of the length     mid_index = length // 2     while mid_index:         head = head.next         mid_index -= 1      # Head now will be pointing to the middle element     return head.data  def main():      # Create a hard-coded linked list:     # 10 -> 20 -> 30 -> 40 -> 50 -> 60     head = Node(10)     head.next = Node(20)     head.next.next = Node(30)     head.next.next.next = Node(40)     head.next.next.next.next = Node(50)     head.next.next.next.next.next = Node(60)      print(getMiddle(head))  if __name__ == "__main__":     main() 
C#
// C# program to illustrate how to find the middle element // by counting the number of nodes using System;  class Node {     public int data;     public Node next;     public Node(int x) {         this.data = x;         this.next = null;     } }  class GfG {      // Helper function to find length of linked list     static int getLength(Node head) {          // Variable to store length         int length = 0;          // Traverse the entire linked list and increment         // length by 1 for each node         while (head != null) {             length++;             head = head.next;         }          // Return the number of nodes in the linked list         return length;     }      // Function to find the middle element of the linked     // list     static int getMiddle(Node head) {          // Finding length of the linked list         int length = getLength(head);          // Traverse till we reach half of the length         int mid_index = length / 2;         while (mid_index-- > 0) {             head = head.next;         }          // Head now will be pointing to the middle element         return head.data;     }      static void Main() {          // Create a hard-coded linked list:         // 10 -> 20 -> 30 -> 40 -> 50 -> 60         Node head = new Node(10);         head.next = new Node(20);         head.next.next = new Node(30);         head.next.next.next = new Node(40);         head.next.next.next.next = new Node(50);         head.next.next.next.next.next = new Node(60);                Console.WriteLine(getMiddle(head));     } } 
JavaScript
// Javascript program to illustrate how to find the middle // element by counting the number of nodes  class Node {     constructor(x) {         this.data = x;         this.next = null;     } }  // Helper function to find length of linked list function getLength(head) {      // Variable to store length     let length = 0;      // Traverse the entire linked list and increment length     // by 1 for each node     while (head) {         length++;         head = head.next;     }      // Return the number of nodes in the linked list     return length; }  // Function to find the middle element of the linked list function getMiddle(head) {      // Finding length of the linked list     const length = getLength(head);      // Traverse till we reach half of the length     let mid_index = Math.floor(length / 2);     while (mid_index-- > 0) {         head = head.next;     }      // Head now will be pointing to the middle element     return head.data; }  function main() {      // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60     const head = new Node(10);     head.next = new Node(20);     head.next.next = new Node(30);     head.next.next.next = new Node(40);     head.next.next.next.next = new Node(50);     head.next.next.next.next.next = new Node(60);      console.log(getMiddle(head)); }  main(); 

Output
40

Time Complexity: O(2 * n) = O(n) where n is the number of nodes in the linked list.
Auxiliary Space: O(1)

[Expected Approach] By Tortoise and Hare Algorithm - O(n) time and O(1) space:

We can use the Hare and Tortoise Algorithm to find the middle of the linked list. Traverse linked list using a slow pointer (slow_ptr) and a fast pointer (fast_ptr ). Move the slow pointer to the next node(one node forward) and the fast pointer to the next of the next node(two nodes forward). When the fast pointer reaches the last node or NULL, then the slow pointer will reach the middle of the linked list.

In case of odd number of nodes in the linked list, slow_ptr will reach the middle node when fast_ptr will reach the last node and in case of even number of nodes in the linked list, slow_ptr will reach the middle node when fast_ptr will become NULL.

Below is the working of above approach:

Code Implementation:

C++
// C++ program to illustrate how to find the middle element // by using Floyd's Cycle Finding Algorithm #include <iostream> using namespace std;  class Node { public:     int data;     Node* next;     Node(int x) {         this->data = x;         this->next = nullptr;     } };  // Function to get the middle of the linked list int getMiddle(Node* head) {        // Initialize the slow and fast pointer to the head of     // the linked list     Node* slow_ptr = head;     Node* fast_ptr = head;      while (fast_ptr != NULL && fast_ptr->next != NULL) {          // Move the fast pointer by two nodes         fast_ptr = fast_ptr->next->next;          // Move the slow pointer by one node         slow_ptr = slow_ptr->next;     }      // Return the slow pointer which is currenlty pointing     // to the middle node of the linked list     return slow_ptr->data; }  int main() {      // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60      Node* head = new Node(10);     head->next = new Node(20);     head->next->next = new Node(30);     head->next->next->next = new Node(40);     head->next->next->next->next = new Node(50);     head->next->next->next->next->next = new Node(60);      cout << getMiddle(head) << endl;      return 0; } 
C
#include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node* next; };  // Function to get the middle of the linked list int getMiddle(struct Node* head) {        // Initialize the slow and fast pointer to the     // head of the linked list     struct Node* slow_ptr = head;     struct Node* fast_ptr = head;      // Traverse the linked list     while (fast_ptr != NULL && fast_ptr->next != NULL) {                // Move the fast pointer by two nodes         fast_ptr = fast_ptr->next->next;          // Move the slow pointer by one node         slow_ptr = slow_ptr->next;     }      // Return the slow pointer which is currently pointing     // to the middle node of the linked list     return slow_ptr->data; }  struct Node* createNode(int x) {     struct Node* newNode =       (struct Node*)malloc(sizeof(struct Node));     newNode->data = x;     newNode->next = NULL;     return newNode; }  int main() {     // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60      struct Node* head = createNode(10);     head->next = createNode(20);     head->next->next = createNode(30);     head->next->next->next = createNode(40);     head->next->next->next->next = createNode(50);     head->next->next->next->next->next = createNode(60);      printf("%d\n", getMiddle(head));      return 0; } 
Java
// Java program to illustrate how to find the middle element // by using Floyd's Cycle Finding Algorithm  class Node {     int data;     Node next;      Node(int x) {         this.data = x;         this.next = null;     } }  class GfG {      // Function to get the middle of the linked list     static int getMiddle(Node head) {          // Initialize the slow and fast pointer to the head         // of the linked list         Node slow_ptr = head;         Node fast_ptr = head;          while (fast_ptr != null && fast_ptr.next != null) {              // Move the fast pointer by two nodes             fast_ptr = fast_ptr.next.next;              // Move the slow pointer by one node             slow_ptr = slow_ptr.next;         }          // Return the slow pointer which is currently         // pointing to the middle node of the linked list         return slow_ptr.data;     }      public static void main(String[] args) {          // Create a hard-coded linked list:         // 10 -> 20 -> 30 -> 40 -> 50 -> 60         Node head = new Node(10);         head.next = new Node(20);         head.next.next = new Node(30);         head.next.next.next = new Node(40);         head.next.next.next.next = new Node(50);         head.next.next.next.next.next = new Node(60);          System.out.println(getMiddle(head));     } } 
Python
# Python program to illustrate how to find the middle element # by using Floyd's Cycle Finding Algorithm  class Node:     def __init__(self, x):         self.data = x         self.next = None  # Function to get the middle of the linked list def getMiddle(head):      # Initialize the slow and fast pointer to the     # head of the linked list     slow_ptr = head     fast_ptr = head      while fast_ptr is not None and fast_ptr.next is not None:          # Move the fast pointer by two nodes         fast_ptr = fast_ptr.next.next          # Move the slow pointer by one node         slow_ptr = slow_ptr.next      # Return the slow pointer which is currently pointing to the     # middle node of the linked list     return slow_ptr.data  def main():      # Create a hard-coded linked list:     # 10 -> 20 -> 30 -> 40 -> 50 -> 60     head = Node(10)     head.next = Node(20)     head.next.next = Node(30)     head.next.next.next = Node(40)     head.next.next.next.next = Node(50)     head.next.next.next.next.next = Node(60)      print(getMiddle(head))  if __name__ == "__main__":     main() 
C#
// C# program to illustrate how to find the middle element // by using Floyd's Cycle Finding Algorithm using System;  class Node {     public int data;     public Node next;     public Node(int x) {         this.data = x;         this.next = null;     } }  class GfG {      // Function to get the middle of the linked list     static int getMiddle(Node head) {          // Initialize the slow and fast pointer to the head         // of the linked list         Node slow_ptr = head;         Node fast_ptr = head;          while (fast_ptr != null && fast_ptr.next != null) {              // Move the fast pointer by two nodes             fast_ptr = fast_ptr.next.next;              // Move the slow pointer by one node             slow_ptr = slow_ptr.next;         }          // Return the slow pointer which is currently         // pointing to the middle node of the linked list         return slow_ptr.data;     }    	// Driver code     static void Main() {          // Create a hard-coded linked list:         // 10 -> 20 -> 30 -> 40 -> 50 -> 60         Node head = new Node(10);         head.next = new Node(20);         head.next.next = new Node(30);         head.next.next.next = new Node(40);         head.next.next.next.next = new Node(50);         head.next.next.next.next.next = new Node(60);          Console.WriteLine(getMiddle(head));     } } 
JavaScript
// Javascript program to illustrate how to find the middle // element by using Floyd's Cycle Finding Algorithm  class Node {     constructor(new_data) {         this.data = new_data;         this.next = null;     } }  // Function to get the middle of the linked list function getMiddle(head) {      // Initialize the slow and fast pointer to the head of     // the linked list     let slow_ptr = head;     let fast_ptr = head;      while (fast_ptr !== null && fast_ptr.next !== null) {          // Move the fast pointer by two nodes         fast_ptr = fast_ptr.next.next;          // Move the slow pointer by one node         slow_ptr = slow_ptr.next;     }      // Return the slow pointer which is currently pointing     // to the middle node of the linked list     return slow_ptr.data; }  function main() {      // Create a hard-coded linked list:     // 10 -> 20 -> 30 -> 40 -> 50 -> 60     const head = new Node(10);     head.next = new Node(20);     head.next.next = new Node(30);     head.next.next.next = new Node(40);     head.next.next.next.next = new Node(50);     head.next.next.next.next.next = new Node(60);      console.log(getMiddle(head)); }  main(); 

Output
Middle Value Of Linked List is: 40 

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)


Next Article
Find Middle of the Linked List

K

kartik
Improve
Article Tags :
  • Linked List
  • DSA
  • Microsoft
  • Amazon
  • Adobe
  • Morgan Stanley
  • Flipkart
  • Qualcomm
  • Samsung
  • VMWare
  • Payu
  • Zoho
  • Hike
  • Nagarro
  • MAQ Software
  • GE
  • Veritas
  • Wipro
  • Python-DSA
Practice Tags :
  • Adobe
  • Amazon
  • Flipkart
  • GE
  • Hike
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Nagarro
  • Payu
  • Qualcomm
  • Samsung
  • Veritas
  • VMWare
  • Wipro
  • Zoho
  • Linked List

Similar Reads

    Linked List of Linked List
    Linked list of linke­d list, also known as nested linke­d lists, is a type of Linked List where each main node stores another full linked list. This structure­ beats old, plain linked lists. It gives way more­ flexibility to store and manage comple­x data. In this article we will learn about the bas
    9 min read
    Make middle node head in a linked list
    Given a singly linked list, find middle of the linked list and set middle node of the linked list at beginning of the linked list. Examples: Input : 1 2 3 4 5 Output : 3 1 2 4 5 Input : 1 2 3 4 5 6 Output : 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one m
    10 min read
    Find extra node in the second Linked list
    Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
    7 min read
    Finding Median in a Sorted Linked List
    Given A sorted linked list of N elements. The task is to find the median in the given Sorted Linked List.We know that median in a sorted array is the middle element. Procedure to find median of N sorted numbers: if N is odd: median is N/2th elementelse median is N/2th element + (N/2+1)th elementExam
    14 min read
    Squareroot(n)-th node in a Linked List
    Given a Linked List, write a function that accepts the head node of the linked list as a parameter and returns the value of node present at (floor(sqrt(n)))th position in the Linked List, where n is the length of the linked list or the total number of nodes in the list. Examples: Input: 1->2->
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences