Find the middle of a given linked list
Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3.
If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list is 1->2->3->4->5->6 then the output should be 4.
Method 1:
Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the node at count/2.
Method 2:
Traverse linked list using two pointers. Move one pointer by one and the other pointers by two. When the fast pointer reaches the end slow pointer will reach the middle of the linked list.
Below image shows how printMiddle function works in the code :
C++
// C++ program for the above approach #include <iostream> using namespace std; class Node{ public : int data; Node *next; }; class NodeOperation{ public : // Function to add a new node void pushNode( class Node** head_ref, int data_val){ // Allocate node class Node *new_node = new Node(); // Put in the data new_node->data = data_val; // Link the old list off the new node new_node->next = *head_ref; // move the head to point to the new node *head_ref = new_node; } // A utility function to print a given linked list void printNode( class Node *head){ while (head != NULL){ cout <<head->data << "->" ; head = head->next; } cout << "NULL" << endl; } void printMiddle( class Node *head){ struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } cout << "The middle element is [" << slow_ptr->data << "]" << endl; } } }; // Driver Code int main(){ class Node *head = NULL; class NodeOperation *temp = new NodeOperation(); for ( int i=5; i>0; i--){ temp->pushNode(&head, i); temp->printNode(head); temp->printMiddle(head); } return 0; } |
C
// C program to find middle of linked list #include<stdio.h> #include<stdlib.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* Function to get the middle of the linked list*/ void printMiddle( struct Node *head) { struct Node *slow_ptr = head; struct Node *fast_ptr = head; if (head!=NULL) { while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; slow_ptr = slow_ptr->next; } printf ( "The middle element is [%d]\n\n" , slow_ptr->data); } } void push( struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = ( struct Node*) malloc ( sizeof ( struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A utility function to print a given linked list void printList( struct Node *ptr) { while (ptr != NULL) { printf ( "%d->" , ptr->data); ptr = ptr->next; } printf ( "NULL\n" ); } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct Node* head = NULL; int i; for (i=5; i>0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; } |
Java
// Java program to find middle of linked list class LinkedList { Node head; // head of linked list /* Linked list node */ class Node { int data; Node next; Node( int d) { data = d; next = null ; } } /* Function to print middle of linked list */ void printMiddle() { Node slow_ptr = head; Node fast_ptr = head; while (fast_ptr != null && fast_ptr.next != null ) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } System.out.println( "The middle element is [" + slow_ptr.data + "] \n" ); } /* Inserts a new Node at front of the list. */ public void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null ) { System.out.print(tnode.data+ "->" ); tnode = tnode.next; } System.out.println( "NULL" ); } public static void main(String [] args) { LinkedList llist = new LinkedList(); for ( int i= 5 ; i> 0 ; --i) { llist.push(i); llist.printList(); llist.printMiddle(); } } } // This code is contributed by Rajat Mishra |
C#
// C# program to find middle of linked list using System; class LinkedList{ // Head of linked list Node head; // Linked list node class Node { public int data; public Node next; public Node( int d) { data = d; next = null ; } } // Function to print middle of linked list void printMiddle() { Node slow_ptr = head; Node fast_ptr = head; if (head != null ) { while (fast_ptr != null && fast_ptr.next != null ) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } Console.WriteLine( "The middle element is [" + slow_ptr.data + "] \n" ); } } // Inserts a new Node at front of the list. public void push( int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // This function prints contents of linked // list starting from the given node public void printList() { Node tnode = head; while (tnode != null ) { Console.Write(tnode.data + "->" ); tnode = tnode.next; } Console.WriteLine( "NULL" ); } // Driver code static public void Main() { LinkedList llist = new LinkedList(); for ( int i = 5; i > 0; --i) { llist.push(i); llist.printList(); llist.printMiddle(); } } } // This code is contributed by Dharanendra L V. |
Python3
# Python3 program to find middle of linked list # Node class class Node: # Function to initialise the node object def __init__( self , data): self .data = data # Assign data self . next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__( self ): self .head = None # Function to insert a new node at the beginning def push( self , new_data): new_node = Node(new_data) new_node. next = self .head self .head = new_node # Print the linked list def printList( self ): node = self .head while node: print ( str (node.data) + "->" , end = "") node = node. next print ( "NULL" ) # Function that returns middle. def printMiddle( self ): # Initialize two pointers, one will go one step a time (slow), another two at a time (fast) slow = self .head fast = self .head # Iterate till fast's next is null (fast reaches end) while fast and fast. next : slow = slow. next fast = fast. next . next # return the slow's data, which would be the middle element. print ( "The middle element is " , slow.data) # Code execution starts here if __name__ = = '__main__' : # Start with the empty list llist = LinkedList() for i in range ( 5 , 0 , - 1 ): llist.push(i) llist.printList() llist.printMiddle() # Code is contributed by Kumar Shivam (kshivi99) |
Javascript
<script> // JavaScript program to find // middle of linked list var head; // head of linked list /* Linked list node */ class Node { constructor(val) { this .data = val; this .next = null ; } } /* Function to print middle of linked list */ function printMiddle() { var slow_ptr = head; var fast_ptr = head; if (head != null ) { while (fast_ptr != null && fast_ptr.next != null ) { fast_ptr = fast_ptr.next.next; slow_ptr = slow_ptr.next; } document.write( "The middle element is [" + slow_ptr.data + "] <br/><br/>" ); } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* * This function prints contents of linked list starting from the given node */ function printList() { var tnode = head; while (tnode != null ) { document.write(tnode.data + "->" ); tnode = tnode.next; } document.write( "NULL<br/>" ); } for (i = 5; i > 0; --i) { push(i); printList(); printMiddle(); } // This code is contributed by todaysgaurav </script> |
5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]
Method 3:
Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list.
Thanks to Narendra Kangralkar for suggesting this method.
C++
#include <bits/stdc++.h> using namespace std; // Link list node struct node { int data; struct node* next; }; // Function to get the middle of // the linked list void printMiddle( struct node* head) { int count = 0; struct node* mid = head; while (head != NULL) { // Update mid, when 'count' // is odd number if (count & 1) mid = mid->next; ++count; head = head->next; } // If empty list is provided if (mid != NULL) printf ( "The middle element is [%d]\n\n" , mid->data); } void push( struct node** head_ref, int new_data) { // Allocate node struct node* new_node = ( struct node*) malloc ( sizeof ( struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to // the new node (*head_ref) = new_node; } // A utility function to print // a given linked list void printList( struct node* ptr) { while (ptr != NULL) { printf ( "%d->" , ptr->data); ptr = ptr->next; } printf ( "NULL\n" ); } // Driver code int main() { // Start with the empty list struct node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; } // This code is contributed by ac121102 |
C
#include <stdio.h> #include <stdlib.h> /* Link list node */ struct node { int data; struct node* next; }; /* Function to get the middle of the linked list*/ void printMiddle( struct node* head) { int count = 0; struct node* mid = head; while (head != NULL) { /* update mid, when 'count' is odd number */ if (count & 1) mid = mid->next; ++count; head = head->next; } /* if empty list is provided */ if (mid != NULL) printf ( "The middle element is [%d]\n\n" , mid->data); } void push( struct node** head_ref, int new_data) { /* allocate node */ struct node* new_node = ( struct node*) malloc ( sizeof ( struct node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // A utility function to print a given linked list void printList( struct node* ptr) { while (ptr != NULL) { printf ( "%d->" , ptr->data); ptr = ptr->next; } printf ( "NULL\n" ); } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct node* head = NULL; int i; for (i = 5; i > 0; i--) { push(&head, i); printList(head); printMiddle(head); } return 0; } |
Java
class GFG{ static Node head; // Link list node class Node { int data; Node next; // Constructor public Node(Node next, int data) { this .data = data; this .next = next; } } // Function to get the middle of // the linked list void printMiddle(Node head) { int count = 0 ; Node mid = head; while (head != null ) { // Update mid, when 'count' // is odd number if ((count % 2 ) == 1 ) mid = mid.next; ++count; head = head.next; } // If empty list is provided if (mid != null ) System.out.println( "The middle element is [" + mid.data + "]\n" ); } void push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(head_ref, new_data); // Move the head to point to the new node head = new_node; } // A utility function to print a // given linked list void printList(Node head) { while (head != null ) { System.out.print(head.data + "-> " ); head = head.next; } System.out.println( "null" ); } // Driver code public static void main(String[] args) { GFG ll = new GFG(); for ( int i = 5 ; i > 0 ; i--) { ll.push(head, i); ll.printList(head); ll.printMiddle(head); } } } // This code is contributed by mark_3 |
Python3
# Node class class Node: # Function to initialise the node object def __init__( self , data): self .data = data # Assign data self . next = None # Initialize next as null # Linked List class contains a Node object class LinkedList: # Function to initialize head def __init__( self ): self .head = None # Function to insert a new node at the beginning def push( self , new_data): new_node = Node(new_data) new_node. next = self .head self .head = new_node # Print the linked list def printList( self ): node = self .head while node: print ( str (node.data) + "->" , end = "") node = node. next print ( "NULL" ) # Function to get the middle of # the linked list def printMiddle( self ): count = 0 mid = self .head heads = self .head while (heads ! = None ): # Update mid, when 'count' # is odd number if count& 1 : mid = mid. next count + = 1 heads = heads. next # If empty list is provided if mid! = None : print ( "The middle element is " , mid.data) # Code execution starts here if __name__ = = '__main__' : # Start with the empty list llist = LinkedList() for i in range ( 5 , 0 , - 1 ): llist.push(i) llist.printList() llist.printMiddle() # This Code is contributed by Manisha_Ediga |
C#
using System; public class GFG { static Node head; // Link list node public class Node { public int data; public Node next; // Constructor public Node(Node next, int data) { this .data = data; this .next = next; } } // Function to get the middle of // the linked list void printMiddle(Node head) { int count = 0; Node mid = head; while (head != null ) { // Update mid, when 'count' // is odd number if ((count % 2) == 1) mid = mid.next; ++count; head = head.next; } // If empty list is provided if (mid != null ) Console.WriteLine( "The middle element is [" + mid.data + "]\n" ); } public void Push(Node head_ref, int new_data) { // Allocate node Node new_node = new Node(head_ref, new_data); // Move the head to point to the new node head = new_node; } // A utility function to print a // given linked list void printList(Node head) { while (head != null ) { Console.Write(head.data + "-> " ); head = head.next; } Console.WriteLine( "null" ); } // Driver code public static void Main(String[] args) { GFG ll = new GFG(); for ( int i = 5; i > 0; i--) { ll.Push(head, i); ll.printList(head); ll.printMiddle(head); } } } // This code is contributed by Rajput-Ji |
Javascript
<script> var head= null ; // Link list node class Node { constructor(next,val) { this .data = val; this .next = next; } } // Function to get the middle of // the linked list function printMiddle(head) { var count = 0; var mid = head; while (head != null ) { // Update mid, when 'count' // is odd number if ((count % 2) == 1) mid = mid.next; ++count; head = head.next; } // If empty list is provided if (mid != null ) document.write( "The middle element is [" + mid.data + "]<br/><br/>" ); } function push(head_ref , new_data) { // Allocate node var new_node = new Node(head_ref, new_data); // Move the head to point to the new node head = new_node; return head; } // A utility function to print a // given linked list function printList(head) { while (head != null ) { document.write(head.data + "-> " ); head = head.next; } document.write( "null<br/>" ); } // Driver code for (i = 5; i > 0; i--) { head= push(head, i); printList(head); printMiddle(head); } // This code contributed by gauravrajput1 </script> |
5->NULL The middle element is [5] 4->5->NULL The middle element is [5] 3->4->5->NULL The middle element is [4] 2->3->4->5->NULL The middle element is [4] 1->2->3->4->5->NULL The middle element is [3]
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.