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:
How to insert a Node in a Singly Linked List at a given Position using Recursion
Next article icon

Insert a node at a specific position in a linked list

Last Updated : 03 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a singly linked list, a position pos, and data, the task is to insert that data into a linked list at the given position. 

Examples:

Input: 3->5->8->10, data = 2, pos = 2
Output: 3->2->5->8->10

Input: 3->5->8->10, data = 11, pos = 5
Output: 3->5->8->10->11 

Insertion-at-a-Specific-Position-of-the-Singly-Linked-List-copy

Insertion at specific position in Linked List

[Expected Approach] Using Iterative Method – O(n) time and O(1) space:

  • Initialize a variable , say curr points to head and allocate the memory to the new node with the given data.
  • Traverse the Linked list using curr pointer upto position-1 nodes.
  • If curr’s next is not null , then next pointer of the new node points to the next of curr node.
  • The next pointer of current node points to the new node.
  • return the head of linked list.

Below is the implementation of the above approach: 

C++
// C++ program for insertion in a single linked // list at a specified position #include <bits/stdc++.h> using namespace std;  class Node {   public:     int data;     Node *next;     Node(int x) {         data = x;         next = nullptr;     } };  // function to insert a Node at required position Node *insertPos(Node *head, int pos, int data) {      // This condition to check whether the     // position given is valid or not.     if (pos < 1)         return head;      // head will change if pos=1     if (pos == 1) {         Node *newNode = new Node(data);         newNode->next = head;         return newNode;     }      Node *curr = head;      // Traverse to the node that will be     // present just before the new node     for (int i = 1; i < pos - 1 && curr != nullptr; i++) {         curr = curr->next;     }          // If position is greater than the      // number of nodes     if (curr == nullptr)          return head;              Node *newNode = new Node(data);      // update the next pointers     newNode->next = curr->next;     curr->next = newNode;      return head; }  void printList(struct Node *head) {     Node *curr = head;     while (curr != nullptr) {         cout << curr->data << " ";         curr = curr->next;     }     cout << endl; }  int main() {      // Creating the list 3->5->8->10     Node *head = new Node(3);     head->next = new Node(5);     head->next->next = new Node(8);     head->next->next->next = new Node(10);      int data = 12, pos = 3;     head = insertPos(head, pos, data);     printList(head);      return 0; } 
C
// C program for insertion in a single linked // list at a specified position #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node *next; };  struct Node *createNode(int x);  // Function to insert a Node at the required position struct Node *insertPos(struct Node *head, int pos, int data) {      // return if invalid input     if (pos < 1)         return head;      // Head will change if pos=1     if (pos == 1) {         struct Node *newNode = createNode(data);         newNode->next = head;         return newNode;     }      struct Node *curr = head;      // Traverse to the node that will be     // present just before the new node     for (int i = 1; i < pos - 1 && curr != NULL; i++) {         curr = curr->next;     }          // if position is greater than     // number of nodes     if (curr == NULL)          return head;              struct Node *newNode = createNode(data);      // Update the next pointers     newNode->next = curr->next;     curr->next = newNode;      return head; }  void printList(struct Node *head) {     struct Node *curr = head;     while (curr != NULL) {         printf("%d ", curr->data);         curr = curr->next;     }     printf("\n"); }  struct Node *createNode(int x) {     struct Node *new_node =        (struct Node *)malloc(sizeof(struct Node));     new_node->data = x;     new_node->next = NULL;     return new_node; }  int main() {      // Creating the list 3->5->8->10     struct Node *head = createNode(3);     head->next = createNode(5);     head->next->next = createNode(8);     head->next->next->next = createNode(10);      int data = 12, pos = 3;     head = insertPos(head, pos, data);     printList(head);      return 0; } 
Java
// Java program for insertion in a single linked // list at a specified position class Node {     int data;     Node next;      Node(int x) {         data = x;         next = null;     } }  class GfG {      // function to insert a Node at required position     static Node insertPos(Node head, int pos, int data) {          // This condition to check whether the         // position given is valid or not.         if (pos < 1)             return head;          // head will change if pos=1         if (pos == 1) {             Node newNode = new Node(data);             newNode.next = head;             return newNode;         }          Node curr = head;          // Traverse to the node that will be          // present just before the new node         for (int i = 1; i < pos - 1 && curr != null; i++) {             curr = curr.next;         }                  // if position is greater than number of elements         if (curr == null)             return head;                  Node newNode = new Node(data);          // update the next pointers         newNode.next = curr.next;         curr.next = newNode;          return head;     }      static void printList(Node node) {         while (node != null) {             System.out.print(node.data + " ");             node = node.next;         }         System.out.println();     }      public static void main(String[] args) {          // Creating the list 3->5->8->10         Node head = new Node(3);         head.next = new Node(5);         head.next.next = new Node(8);         head.next.next.next = new Node(10);          int data = 12, pos = 3;         head = insertPos(head, pos, data);         printList(head);     } } 
Python
# Python program for insertion in a single linked # list at a specified position  class Node:     def __init__(self, x):         self.data = x         self.next = None  # function to insert a Node at required position def insert_pos(head, pos, data):          # This condition to check whether the     # position given is valid or not.     if pos < 1:         return head          # head will change if pos=1     if pos == 1:         new_node = Node(data)         new_node.next = head         return new_node          curr = head          # Traverse to the node that will be      # present just before the new node     for _ in range(1, pos - 1):         if curr == None:             break         curr = curr.next              # if position is greater     # number of nodes     if curr is None:         return head          new_node = Node(data)          # update the next pointers     new_node.next = curr.next     curr.next = new_node          return head      def print_list(head):     curr = head     while curr is not None:         print(curr.data, end=" ")         curr = curr.next     print()  if __name__ == "__main__":          # Creating the list 3->5->8->10     head = Node(3)     head.next = Node(5)     head.next.next = Node(8)     head.next.next.next = Node(10)      data = 12     pos = 3     head = insert_pos(head, pos, data)     print_list(head) 
C#
// C# program for insertion in a single linked // list at a specified position using System;  class Node {     public int data;     public Node next;      public Node(int x) {         data = x;         next = null;     } }  class GfG {      // function to insert a Node at required position     static Node InsertPos(Node head, int pos, int data) {          // This condition to check whether the         // position given is valid or not.         if (pos < 1)             return head;          // head will change if pos=1         if (pos == 1) {             Node newHead = new Node(data);             newHead.next = head;             return newHead;         }          Node curr = head;          // Traverse to the node that will be          // present just before the new node         for (int i = 1; i < pos - 1 && curr != null; i++) {             curr = curr.next;         }                  // if position is greater than         // size of list         if (curr == null)             return head;                  Node newNode = new Node(data);          // update the next pointers         newNode.next = curr.next;         curr.next = newNode;          return head;     }      static void PrintList(Node head) {         Node curr = head;         while (curr != null) {             Console.Write(curr.data + " ");             curr = curr.next;         }         Console.WriteLine();     }      static void Main() {          // Creating the list 3->5->8->10         Node head = new Node(3);         head.next = new Node(5);         head.next.next = new Node(8);         head.next.next.next = new Node(10);          int data = 12, pos = 3;         head = InsertPos(head, pos, data);         PrintList(head);     } } 
JavaScript
// JavaScript program for insertion in a single linked // list at a specified position  class Node {     constructor(x) {         this.data = x;         this.next = null;     } }  // function to insert a Node at required position function insertPos(head, pos, data) {          // This condition to check whether the     // position given is valid or not.     if (pos < 1)         return head;          // head will change if pos=1     if (pos === 1) {         let newNode = new Node(data);         newNode.next = head;         return newNode;     }          let curr = head;          // Traverse to the node that will be      // present just before the new node     for (let i = 1; i < pos - 1 && curr != null; i++) {         curr = curr.next;     }          // if position is greater     // than size of list     if (curr == null)         return head;              let newNode = new Node(data);          // update the next pointers     newNode.next = curr.next;     curr.next = newNode;          return head; }  function printList(head) {     let curr = head;     while (curr !== null) {         console.log(curr.data);         curr = curr.next;     } }  // Creating the list 3->5->8->10 let head = new Node(3); head.next = new Node(5); head.next.next = new Node(8); head.next.next.next = new Node(10);  let data = 12, pos = 3; head = insertPos(head, pos, data); printList(head); 

Output
3 5 12 8 10  

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



Next Article
How to insert a Node in a Singly Linked List at a given Position using Recursion

P

Prasoon_Mishra
Improve
Article Tags :
  • DSA
  • Linked List
Practice Tags :
  • Linked List

Similar Reads

  • Insert a Node at a specific position in Doubly Linked List
    Given a Doubly Linked List, the task is to insert a new node at a specific position in the linked list.  Examples: Input: Linked List = 1 <-> 2 <-> 4, newData = 3, position = 3Output: Linked List = 1 <-> 2 <-> 3 <-> 4Explanation: New node with data = 3 is inserted at po
    13 min read
  • XOR Linked List - Insert an element at a specific position
    Given a XOR linked list and two integers position and value, the task is to insert a node containing value as the positionth node of the XOR Linked List. Examples: Input: 4<-->7<-->9<-->7, position = 3, value = 6 Output: 4<-->7<-->6<-->9<-->7Explanation: Ins
    15+ min read
  • Insertion at specific position in circular linked list
    Inserting an element at a specific position in a circular linked list is a common operation that involves adjusting pointers in a circular structure. Unlike a regular linked list, where the last node points to NULL, a circular linked list’s last node points back to the head, forming a loop. This pro
    10 min read
  • Insertion at Specific Position in a Circular Doubly Linked List
    Prerequisite: Insert Element Circular Doubly Linked List.Convert an Array to a Circular Doubly Linked List.Given the start pointer pointing to the start of a Circular Doubly Linked List, an element and a position. The task is to insert the element at the specified position in the given Circular Doub
    15+ min read
  • How to insert a Node in a Singly Linked List at a given Position using Recursion
    Given a singly linked list as list, a position, and a node, the task is to insert that element in the given linked list at a given position using recursion. Examples: Input: list = 1->2->3->4->5->6->7, node = (val=100,next=null), position = 4 Output: 1->2->3->100->4-
    14 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 -> 1 Input: LinkedList = NULL, NewNode = 1Output: LinkedList = 1 Approach:  Inserting at the end
    9 min read
  • Delete a Linked List node at a given position
    Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position. Note: Position will be valid (i.e, 1 <= position <= linked list length) Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8-
    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 ->
    11 min read
  • Insert a Node at Front/Beginning of a Linked List
    Given a linked list, the task is to insert a new node at the beginning/start/front of the linked list. Example: Input: LinkedList = 2->3->4->5, NewNode = 1Output: 1 2 3 4 5 Input: LinkedList = 2->10, NewNode = 1Output: 1 2 10 Approach: To insert a new node at the front, we create a new n
    8 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
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