Find Middle of the Linked List
Last Updated :
04 Sep, 2024
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.
[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();
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();
OutputMiddle 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)
Finding middle element in a Linked list
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem