[Approach] Using Iterative Method - O(n) time and O(1) space:
The idea is simple: create a new node, then find the spot where it should be placed. Walk through the list until you reach the node just before that position. Link the new node’s next to the following node, and adjust the previous node’s next to point to the new node.
Step By Step Implementations:
Initialize a variable , say curr points to head and allocate the memory to the new node with the given val.
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.
C++
#include<iostream>usingnamespacestd;classNode{public:intval;Node*next;Node(intx){val=x;next=nullptr;}};Node*insertPos(Node*head,intpos,intval){if(pos<1)returnhead;// head will change if pos=1if(pos==1){Node*newNode=newNode(val);newNode->next=head;returnnewNode;}Node*curr=head;// Traverse to the node that will be// present just before the new nodefor(inti=1;i<pos-1&&curr!=nullptr;i++){curr=curr->next;}// If position is greater than the // number of nodesif(curr==nullptr)returnhead;Node*newNode=newNode(val);// update the next pointersnewNode->next=curr->next;curr->next=newNode;returnhead;}voidprintList(Node*head){Node*curr=head;while(curr!=nullptr){cout<<curr->val;if(curr->next!=nullptr){cout<<" -> ";}curr=curr->next;}cout<<endl;}intmain(){// Creating the list 1->2->4Node*head=newNode(1);head->next=newNode(2);head->next->next=newNode(4);intval=3,pos=3;head=insertPos(head,pos,val);printList(head);return0;}
C
#include<stdio.h>#include<stdlib.h>// Define a linked list nodestructNode{intval;structNode*next;};// Function to create a new nodestructNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->val=x;newNode->next=NULL;returnnewNode;}// Function to insert a new node at a specific positionstructNode*insertPos(structNode*head,intpos,intval){if(pos<1)returnhead;// If inserting at the headif(pos==1){structNode*newNode=createNode(val);newNode->next=head;returnnewNode;}structNode*curr=head;// Traverse to the node just before the new positionfor(inti=1;i<pos-1&&curr!=NULL;i++){curr=curr->next;}// If position is greater than the number of nodesif(curr==NULL)returnhead;// Create and insert the new nodestructNode*newNode=createNode(val);newNode->next=curr->next;curr->next=newNode;returnhead;}// Function to print the linked listvoidprintList(structNode*head){structNode*curr=head;while(curr!=NULL){printf("%d",curr->val);if(curr->next!=NULL)printf(" -> ");curr=curr->next;}printf("\n");}intmain(){// Creating the list 1->2->4structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(4);intval=3,pos=3;// Insert at the given positionhead=insertPos(head,pos,val);// Print the final listprintList(head);return0;}
Java
classNode{intval;Nodenext;Node(intx){val=x;next=null;}}classGfG{staticNodeinsertPos(Nodehead,intpos,intval){if(pos<1)returnhead;// head will change if pos=1if(pos==1){NodenewNode=newNode(val);newNode.next=head;returnnewNode;}Nodecurr=head;// Traverse to the node that will be// present just before the new nodefor(inti=1;i<pos-1&&curr!=null;i++){curr=curr.next;}// If position is greater than the// number of nodesif(curr==null)returnhead;NodenewNode=newNode(val);// update the next pointersnewNode.next=curr.next;curr.next=newNode;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){System.out.print(curr.val);if(curr.next!=null){System.out.print(" -> ");}curr=curr.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating the list 1->2->4Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);intval=3,pos=3;head=insertPos(head,pos,val);printList(head);}}
Python
classNode:def__init__(self,x):self.val=xself.next=NonedefinsertPos(head,pos,val):ifpos<1:returnhead# head will change if pos = 1ifpos==1:newNode=Node(val)newNode.next=headreturnnewNodecurr=head# Traverse to the node just before the new nodeforiinrange(1,pos-1):ifcurrisNone:returnheadcurr=curr.next# If position is greater than number of nodesifcurrisNone:returnheadnewNode=Node(val)# update the next pointersnewNode.next=curr.nextcurr.next=newNodereturnheaddefprintList(head):curr=headwhilecurr:print(curr.val,end="")ifcurr.next:print(" -> ",end="")curr=curr.nextprint()if__name__=="__main__":# Creating the list 1->2->4head=Node(1)head.next=Node(2)head.next.next=Node(4)val,pos=3,3head=insertPos(head,pos,val)printList(head)
C#
usingSystem;classNode{publicintval;publicNodenext;publicNode(intx){val=x;next=null;}}classGfG{staticNodeinsertPos(Nodehead,intpos,intval){if(pos<1)returnhead;// head will change if pos = 1if(pos==1){NodenewNode=newNode(val);newNode.next=head;returnnewNode;}Nodecurr=head;// Traverse to the node just before the new nodefor(inti=1;i<pos-1&&curr!=null;i++){curr=curr.next;}// If position is greater than number of nodesif(curr==null)returnhead;NodenewNode2=newNode(val);// update the next pointersnewNode2.next=curr.next;curr.next=newNode2;returnhead;}staticvoidprintList(Nodehead){Nodecurr=head;while(curr!=null){Console.Write(curr.val);if(curr.next!=null){Console.Write(" -> ");}curr=curr.next;}Console.WriteLine();}staticvoidMain(string[]args){// Creating the list 1->2->4Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);intval=3,pos=3;head=insertPos(head,pos,val);printList(head);}}
JavaScript
classNode{constructor(x){this.val=x;this.next=null;}}functioninsertPos(head,pos,val){if(pos<1)returnhead;// head will change if pos = 1if(pos===1){letnewNode=newNode(val);newNode.next=head;returnnewNode;}letcurr=head;// Traverse to the node just before the new nodefor(leti=1;i<pos-1&&curr!==null;i++){curr=curr.next;}// If position is greater than number of nodesif(curr===null)returnhead;letnewNode=newNode(val);// update the next pointersnewNode.next=curr.next;curr.next=newNode;returnhead;}functionprintList(head){letcurr=head;while(curr!==null){process.stdout.write(curr.val.toString());if(curr.next!==null){process.stdout.write(" -> ");}curr=curr.next;}console.log();}// Driver code// Creating the list 1->2->4lethead=newNode(1);head.next=newNode(2);head.next.next=newNode(4);letval=3,pos=3;head=insertPos(head,pos,val);printList(head);