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:
Make middle node head in a linked list
Next article icon

Make middle node head in a linked list

Last Updated : 20 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 

https://media.geeksforgeeks.org/wp-content/uploads/Capturedsdw.png

The idea is to first find middle of a linked list using two pointers, first one moves one at a time and second one moves two at a time. When second pointer reaches end, first reaches middle. We also keep track of previous of first pointer so that we can remove middle node from its current position and can make it head. 

Implementation:

C++
// C++ program to make middle node as head of  // linked list.  #include <bits/stdc++.h> using namespace std;  /* Link list node */ class Node  {      public:     int data;      Node* next;  };   /* Function to get the middle and set at  beginning of the linked list*/ void setMiddleHead(Node** head)  {      if (*head == NULL)          return;       // To traverse list nodes one by one      Node* one_node = (*head);       // To traverse list nodes by skipping      // one.      Node* two_node = (*head);       // To keep track of previous of middle      Node* prev = NULL;      while (two_node != NULL && two_node->next != NULL)      {           /* for previous node of middle node */         prev = one_node;           /* move one node each time*/         two_node = two_node->next->next;           /* move two node each time*/         one_node = one_node->next;      }       /* set middle node at head */     prev->next = prev->next->next;      one_node->next = (*head);      (*head) = one_node;  }   // To insert a node at the beginning of linked  // list.  void push(Node** head_ref, int new_data)  {      /* allocate node */     Node* new_node = new Node();       new_node->data = new_data;       /* link the old list of the new node */     new_node->next = (*head_ref);       /* move the head to point to the new node */     (*head_ref) = new_node;  }   // A function to print a given linked list  void printList(Node* ptr)  {      while (ptr != NULL)     {          cout << ptr->data << " ";          ptr = ptr->next;      }      cout<<endl;  }   /* Driver code*/ int main()  {      // Create a list of 5 nodes      Node* head = NULL;      int i;      for (i = 5; i > 0; i--)          push(&head, i);       cout << " list before: ";      printList(head);       setMiddleHead(&head);       cout << " list After: ";      printList(head);       return 0;  }   // This is code is contributed by rathbhupendra 
C
// C program to make middle node as head of // linked list. #include <stdio.h> #include <stdlib.h>  /* Link list node */ struct Node {     int data;     struct Node* next; };  /* Function to get the middle and set at    beginning of the linked list*/ void setMiddleHead(struct Node** head) {     if (*head == NULL)         return;      // To traverse list nodes one by one     struct Node* one_node = (*head);      // To traverse list nodes by skipping     // one.     struct Node* two_node = (*head);      // To keep track of previous of middle     struct Node* prev = NULL;     while (two_node != NULL && two_node->next != NULL) {          /* for previous node of middle node */         prev = one_node;          /* move one node each time*/         two_node = two_node->next->next;          /* move two node each time*/         one_node = one_node->next;     }      /* set middle node at head */     prev->next = prev->next->next;     one_node->next = (*head);     (*head) = one_node; }  // To insert a node at the beginning of linked // list. void push(struct Node** head_ref, int new_data) {     /* allocate node */     struct Node* new_node =         (struct Node*)malloc(sizeof(struct Node));      new_node->data = new_data;      /* link the old list of the new node */     new_node->next = (*head_ref);      /* move the head to point to the new node */     (*head_ref) = new_node; }  // A  function to print a given linked list void printList(struct Node* ptr) {     while (ptr != NULL) {         printf("%d ", ptr->data);         ptr = ptr->next;     }     printf("\n"); }  /* Driver function*/ int main() {     // Create a list of 5 nodes     struct Node* head = NULL;     int i;     for (i = 5; i > 0; i--)         push(&head, i);      printf(" list before: ");     printList(head);      setMiddleHead(&head);      printf(" list After:  ");     printList(head);      return 0; } 
Java
// Java program to make middle node  // as head of Linked list public class GFG  {          /* Link list node */     static class Node {         int data;         Node next;         Node(int data){             this.data = data;             next = null;         }     }          static Node head;          /* Function to get the middle and      set at beginning of the linked list*/     static void setMiddleHead()     {         if (head == null)             return;               // To traverse list nodes one          // by one         Node one_node = head;               // To traverse list nodes by          // skipping one.         Node two_node = head;               // To keep track of previous of middle         Node prev = null;         while (two_node != null &&                 two_node.next != null) {                   /* for previous node of middle node */             prev = one_node;                   /* move one node each time*/             two_node = two_node.next.next;                   /* move two node each time*/             one_node = one_node.next;         }               /* set middle node at head */         prev.next = prev.next.next;         one_node.next = head;         head = one_node;     }           // To insert a node at the beginning of     // linked list.     static void push(int new_data)     {         /* allocate node */         Node new_node = new Node(new_data);               /* link the old list of the new node */         new_node.next = head;               /* move the head to point to the new node */         head = new_node;     }           // A  function to print a given linked list     static void printList(Node ptr)     {         while (ptr != null) {             System.out.print(ptr.data+" ");             ptr = ptr.next;         }         System.out.println();     }           /* Driver function*/     public static void main(String args[])     {         // Create a list of 5 nodes         head = null;         int i;         for (i = 5; i > 0; i--)             push(i);                  System.out.print(" list before: ");         printList(head);               setMiddleHead();               System.out.print(" list After:  ");         printList(head);          } } // This code is contributed by Sumit Ghosh 
Python3
# Python3 program to make middle node # as head of Linked list  # Linked List node class Node:     def __init__(self, data):         self.data = data         self.next = None  # function to get the middle node # set it as the beginning of the  # linked list def setMiddleHead(head):     if(head == None):         return None      # to traverse nodes      # one by one     one_node = head      # to traverse nodes by      # skipping one     two_node = head      # to keep track of previous middle     prev = None      while(two_node != None and           two_node.next != None):          # for previous node of middle node         prev = one_node          # move one node each time         one_node = one_node.next          # move two nodes each time         two_node = two_node.next.next      # set middle node at head     prev.next = prev.next.next     one_node.next = head     head = one_node      # return the modified head     return head  def push(head, new_data):      # allocate new node     new_node = Node(new_data)      #link the old list to new node     new_node.next = head      # move the head to point the new node     head = new_node      # return the modified head     return head  # A function to print a given linked list def printList(head):     temp = head     while (temp!=None):                  print(str(temp.data), end = " ")         temp = temp.next     print("")  # Create a list of 5 nodes head = None for i in range(5, 0, -1):     head = push(head, i)  print(" list before: ", end = "") printList(head)  head = setMiddleHead(head)  print(" list After: ", end = "") printList(head)  # This code is contributed # by Pranav Devarakonda 
C#
// C# program to make middle node  // as head of Linked list using System;  public class GFG  {          /* Link list node */     class Node      {         public int data;         public Node next;         public Node(int data)         {             this.data = data;             next = null;         }     }          static Node head;          /* Function to get the middle and      set at beginning of the linked list*/     static void setMiddleHead()     {         if (head == null)             return;              // To traverse list nodes one          // by one         Node one_node = head;              // To traverse list nodes by          // skipping one.         Node two_node = head;              // To keep track of previous of middle         Node prev = null;         while (two_node != null &&              two_node.next != null)          {                  /* for previous node of middle node */             prev = one_node;                  /* move one node each time*/             two_node = two_node.next.next;                  /* move two node each time*/             one_node = one_node.next;         }              /* set middle node at head */         prev.next = prev.next.next;         one_node.next = head;         head = one_node;     }          // To insert a node at the beginning of     // linked list.     static void push(int new_data)     {         /* allocate node */         Node new_node = new Node(new_data);              /* link the old list of the new node */         new_node.next = head;              /* move the head to point to the new node */         head = new_node;     }          // A function to print a given linked list     static void printList(Node ptr)     {         while (ptr != null) {             Console.Write(ptr.data + " ");             ptr = ptr.next;         }         Console.WriteLine();     }          /* Driver code*/     public static void Main(String []args)     {         // Create a list of 5 nodes         head = null;         int i;         for (i = 5; i > 0; i--)             push(i);                  Console.Write(" list before: ");         printList(head);              setMiddleHead();              Console.Write(" list After: ");         printList(head);     } }  // This code is contributed by Rajput-Ji 
JavaScript
<script> // javascript program to make middle node  // as head of Linked list      /* Link list node */ class Node {     constructor(val) {         this.data = val;         this.next = null;     } }      var head;      /*      * Function to get the middle and set at beginning of the linked list      */     function setMiddleHead() {         if (head == null)             return;          // To traverse list nodes one         // by one          one_node = head;          // To traverse list nodes by         // skipping one.          two_node = head;          // To keep track of previous of middle          prev = null;         while (two_node != null && two_node.next != null) {              /* for previous node of middle node */             prev = one_node;              /* move one node each time */             two_node = two_node.next.next;              /* move two node each time */             one_node = one_node.next;         }          /* set middle node at head */         prev.next = prev.next.next;         one_node.next = head;         head = one_node;     }      // To insert a node at the beginning of     // linked list.     function push(new_data)     {              /* allocate node */          new_node = new Node(new_data);          /* link the old list of the new node */         new_node.next = head;          /* move the head to point to the new node */         head = new_node;     }      // A function to print a given linked list     function printList( ptr) {         while (ptr != null) {             document.write(ptr.data + " ");             ptr = ptr.next;         }         document.write("<br/>");     }      /* Driver function */              // Create a list of 5 nodes         head = null;         var i;         for (i = 5; i > 0; i--)             push(i);          document.write(" list before: ");         printList(head);          setMiddleHead();          document.write(" list After:  ");         printList(head);  // This code is contributed by aashish1995  </script> 

Output
 list before: 1 2 3 4 5   list After: 3 1 2 4 5 

Time Complexity : O(n) 
Auxiliary Space : O(1)

 


Next Article
Make middle node head in a linked list

R

R_Raj
Improve
Article Tags :
  • Misc
  • Linked List
  • DSA
  • Tortoise-Hare-Approach
Practice Tags :
  • Linked List
  • Misc

Similar Reads

    Javascript Program For Making 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 5Input: 1 2 3 4 5 6Output: 4 1 2 3 5 6 The idea is to first find middle of a linked list using two pointers, first one moves on
    3 min read
    Insert Node at the End of a Linked List
    Given a linked list, the task is to insert a new node at the end of the linked list.Examples:Input: LinkedList = 2 -> 3 -> 4 -> 5, NewNode = 1Output: LinkedList = 2 -> 3 -> 4 -> 5 -> 1Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1Approach: Inserting at the end invol
    9 min read
    Make a loop at k-th position in a linked list
    Given a linked list and a position k. Make a loop at k-th position Examples: Input : Given linked list Output : Modified linked list Algorithm: Traverse the first linked list till k-th point Make backup of the k-th node Traverse the linked list till end Attach the last node with k-th node Implementa
    8 min read
    Insert a Node after a given Node in Linked List
    Given a linked list, the task is to insert a new node after a given node of the linked list. If the given node is not present in the linked list, print "Node not found".Examples:Input: LinkedList = 2 -> 3 -> 4 -> 5, newData = 1, key = 2Output: LinkedList = 2 -> 1 -> 3 -> 4 -> 5I
    11 min read
    Insert a Node at the end of Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node at the end of the linked list.Examples: Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4Output: Linked List = 1 <-> 2 <-> 3 <-> 4Input: Linked List = NULL, NewNode = 1Output: Linked List = 1Approach: Inserting
    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