Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
C++ Program For Inserting A Node In A Linked List
Next article icon

C++ Program For Inserting Node In The Middle Of The Linked List

Last Updated : 10 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node.

Examples: 

Input : list: 1->2->4->5         x = 3 Output : 1->2->3->4->5  Input : list: 5->10->4->32->16         x = 41 Output : 5->10->4->41->32->16
Recommended: Please solve it on PRACTICE first, before moving on to the solution.

Method 1(Using length of the linked list): 
Find the number of nodes or length of the linked using one traversal. Let it be len. Calculate c = (len/2), if len is even, else c = (len+1)/2, if len is odd. Traverse again the first c nodes and insert the new node after the cth node.  

C++
// C++ implementation to insert node at the middle // of the linked list #include <bits/stdc++.h>  using namespace std;  // structure of a node struct Node {     int data;     Node* next; };  // function to create and return a node Node* getNode(int data) {     // allocating space     Node* newNode = (Node*)malloc(sizeof(Node));      // inserting the required data     newNode->data = data;     newNode->next = NULL;     return newNode; }  // function to insert node at the middle // of the linked list void insertAtMid(Node** head_ref, int x) {     // if list is empty     if (*head_ref == NULL)         *head_ref = getNode(x);     else {          // get a new node         Node* newNode = getNode(x);          Node* ptr = *head_ref;         int len = 0;          // calculate length of the linked list         //, i.e, the number of nodes         while (ptr != NULL) {             len++;             ptr = ptr->next;         }          // 'count' the number of nodes after which         //  the new node is to be inserted         int count = ((len % 2) == 0) ? (len / 2) :                                     (len + 1) / 2;         ptr = *head_ref;          // 'ptr' points to the node after which          // the new node is to be inserted         while (count-- > 1)             ptr = ptr->next;          // insert the 'newNode' and adjust the         // required links         newNode->next = ptr->next;         ptr->next = newNode;     } }  // function to display the linked list void display(Node* head) {     while (head != NULL) {         cout << head->data << " ";         head = head->next;     } }  // Driver program to test above int main() {     // Creating the list 1->2->4->5     Node* head = NULL;     head = getNode(1);     head->next = getNode(2);     head->next->next = getNode(4);     head->next->next->next = getNode(5);      cout << "Linked list before insertion: ";     display(head);      int x = 3;     insertAtMid(&head, x);      cout << " Linked list after insertion: ";     display(head);      return 0; } 

Output: 

Linked list before insertion: 1 2 4 5 Linked list after insertion: 1 2 3 4 5

Time Complexity: O(n)

Space complexity: O(1) since using constant space

Method 2(Using two pointers): 
Based on the tortoise and hare algorithm which uses two pointers, one known as slow and the other known as fast. This algorithm helps in finding the middle node of the linked list. It is explained in the front and black split procedure of this post. Now, you can insert the new node after the middle node obtained from the above process. This approach requires only a single traversal of the list. 

C++
// C++ implementation to insert node at the middle // of the linked list #include <bits/stdc++.h>  using namespace std;  // structure of a node struct Node {     int data;     Node* next; };  // function to create and return a node Node* getNode(int data) {     // allocating space     Node* newNode = (Node*)malloc(sizeof(Node));      // inserting the required data     newNode->data = data;     newNode->next = NULL;     return newNode; }  // function to insert node at the middle // of the linked list void insertAtMid(Node** head_ref, int x) {     // if list is empty     if (*head_ref == NULL)         *head_ref = getNode(x);      else {         // get a new node         Node* newNode = getNode(x);          // assign values to the slow and fast          // pointers         Node* slow = *head_ref;         Node* fast = (*head_ref)->next;          while (fast && fast->next) {              // move slow pointer to next node             slow = slow->next;              // move fast pointer two nodes at a time             fast = fast->next->next;         }          // insert the 'newNode' and adjust the         // required links         newNode->next = slow->next;         slow->next = newNode;     } }  // function to display the linked list void display(Node* head) {     while (head != NULL) {         cout << head->data << " ";         head = head->next;     } }  // Driver program to test above int main() {     // Creating the list 1->2->4->5     Node* head = NULL;     head = getNode(1);     head->next = getNode(2);     head->next->next = getNode(4);     head->next->next->next = getNode(5);      cout << "Linked list before insertion: ";     display(head);      int x = 3;     insertAtMid(&head, x);      cout << " Linked list after insertion: ";     display(head);      return 0; } 

Output: 

Linked list before insertion: 1 2 4 5 Linked list after insertion: 1 2 3 4 5

Time Complexity: O(n)

Space complexity: O(n) where n is size of linked list

Please refer complete article on Insert node into the middle of the linked list for more details!


Next Article
C++ Program For Inserting A Node In A Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • C++ Programs
  • DSA
  • Tortoise-Hare-Approach
Practice Tags :
  • Linked List

Similar Reads

  • C++ Program For Inserting A Node In A Linked List
    Inserting a node into a linked list can be done in several ways, depending on where we want to insert the new node. Here, we'll cover four common scenarios: inserting at the front of the list, after a given node, at a specific position, and at the end of the list Table of Content Insert a Node at th
    9 min read
  • C++ Program To Find The Sum Of Last N Nodes Of The Given Linked List
    Given a linked list and a number n. Find the sum of the last n nodes of the linked list.Constraints: 0 <= n <= number of nodes in the linked list. Examples: Input: 10->6->8->4->12, n = 2 Output: 16 Sum of last two nodes: 12 + 4 = 16 Input: 15->7->9->5->16->14, n = 4
    10 min read
  • C++ 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 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 moves
    3 min read
  • C++ Program For Insertion Sort In A Singly Linked List
    We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
    5 min read
  • C++ Program To Delete Middle Of Linked List
    Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
    4 min read
  • C++ Program To Delete N Nodes After M Nodes Of A Linked List
    Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same till end of the linked list.Difficulty Level: Rookie Examples: Input: M = 2, N = 2 Linked List: 1->2->3->4->5->6->7->8 Output: Linked L
    3 min read
  • C++ Program For Inserting A Node After The N-th Node From The End
    Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has
    5 min read
  • C++ Program For Writing A Function To Get Nth Node In A Linked List
    Write a C++ Program to GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position. Example: Input: 1->10->30->14, index = 2Output: 30 The node at index 2 is 30Recommended: Please solve it on "PRACTICE" first, before m
    4 min read
  • C++ Program For Removing Middle Points From a Linked List Of Line Segments
    Given a linked list of coordinates where adjacent points either form a vertical line or a horizontal line. Delete points from the linked list which are in the middle of a horizontal or vertical line.Examples: Input: (0,10)->(1,10)->(5,10)->(7,10) | (7,5)->(20,5)->(40,5) Output: Linked
    4 min read
  • Insert N elements in a Linked List one after other at middle position
    Given an array of N elements. The task is to insert the given elements at the middle position in the linked list one after another. Each insert operation should take O(1) time complexity.Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 1 -> 3 -> 5 -> 4 -> 2 -> NULL 1 -> NULL 1 -
    10 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