Given the head of a doubly-linked list, a position p, and an integer x. Insert a new node with value x at the position just after pth node (0-based indexing) in the doubly linked list and return the head of the modified list.
Examples:
Input: p = 2, x = 6
Output: 2 <-> 4 <-> 5 <-> 6 Explanation: Insert a node of value 6 after the 2nd node.
Input: p = 0, x = 44
Output: 1 <-> 44 <-> 2 <-> 3 <-> 4 Explanation: Insert a node of value 44 after the 0th node.
[Naive Approach] Using Auxiliary Array - O(n) Time and O(n) Space
The idea is to first store all the nodes of the doubly linked list in an array. This allows direct access to the p-th node, after which the new node is inserted by updating the required next and prev pointers.
Working of Approach:
Traverse the list and store each node in an array.
Access the p-th node directly from the array.
Create a new node with value x.
Update the next and prev pointers to insert the new node.
Return the head of the modified list.
C++
#include<iostream>#include<vector>usingnamespacestd;classNode{public:intdata;Node*next;Node*prev;Node(intx){data=x;next=prev=nullptr;}};Node*insertAtPos(Node*head,intp,intx){// Store all nodes in an arrayvector<Node*>nodes;Node*curr=head;while(curr){nodes.push_back(curr);curr=curr->next;}// Create new nodeNode*newNode=newNode(x);// Get p-th nodeNode*pNode=nodes[p];// Insert new nodenewNode->next=pNode->next;newNode->prev=pNode;if(pNode->next)pNode->next->prev=newNode;pNode->next=newNode;returnhead;}// Function to print the doubly linked listvoidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" <-> ";head=head->next;}cout<<endl;}intmain(){// Creating linked list: 2 <-> 4 <-> 5Node*head=newNode(2);head->next=newNode(4);head->next->prev=head;head->next->next=newNode(5);head->next->next->prev=head->next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);return0;}
Java
importjava.util.ArrayList;classNode{publicintdata;publicNodenext;publicNodeprev;publicNode(intx){data=x;next=prev=null;}}publicclassGFG{publicstaticNodeinsertAtPos(Nodehead,intp,intx){// Store all nodes in an arrayArrayList<Node>nodes=newArrayList<>();Nodecurr=head;while(curr!=null){nodes.add(curr);curr=curr.next;}// Create new nodeNodenewNode=newNode(x);// Get p-th nodeNodepNode=nodes.get(p);// Insert new nodenewNode.next=pNode.next;newNode.prev=pNode;if(pNode.next!=null)pNode.next.prev=newNode;pNode.next=newNode;returnhead;}// Function to print the doubly linked listpublicstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" <-> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating linked list: 2 <-> 4 <-> 5Nodehead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.next=Noneself.prev=NonedefinsertAtPos(head,p,x):# Store all nodes in an arraynodes=[]curr=headwhilecurrisnotNone:nodes.append(curr)curr=curr.next# Create new nodenewNode=Node(x)# Get p-th nodepNode=nodes[p]# Insert new nodenewNode.next=pNode.nextnewNode.prev=pNodeifpNode.nextisnotNone:pNode.next.prev=newNodepNode.next=newNodereturnhead# Function to print the doubly linked listdefprintList(head):whileheadisnotNone:print(head.data,end='')ifhead.nextisnotNone:print(' <-> ',end='')head=head.nextprint()if__name__=='__main__':# Creating linked list: 2 <-> 4 <-> 5head=Node(2)head.next=Node(4)head.next.prev=headhead.next.next=Node(5)head.next.next.prev=head.nextp=2x=6head=insertAtPos(head,p,x)printList(head)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodenext;publicNodeprev;publicNode(intx){data=x;next=prev=null;}}publicclassGFG{publicstaticNodeinsertAtPos(Nodehead,intp,intx){// Store all nodes in an arrayList<Node>nodes=newList<Node>();Nodecurr=head;while(curr!=null){nodes.Add(curr);curr=curr.next;}// Create new nodeNodenewNode=newNode(x);// Get p-th nodeNodepNode=nodes[p];// Insert new nodenewNode.next=pNode.next;newNode.prev=pNode;if(pNode.next!=null)pNode.next.prev=newNode;pNode.next=newNode;returnhead;}// Function to print the doubly linked listpublicstaticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" <-> ");head=head.next;}Console.WriteLine();}publicstaticvoidMain(){// Creating linked list: 2 <-> 4 <-> 5Nodehead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;this.prev=null;}}functioninsertAtPos(head,p,x){// Store all nodes in an arrayletnodes=[];letcurr=head;while(curr!==null){nodes.push(curr);curr=curr.next;}// Create new nodeletnewNode=newNode(x);// Get p-th nodeletpNode=nodes[p];// Insert new nodenewNode.next=pNode.next;newNode.prev=pNode;if(pNode.next!==null)pNode.next.prev=newNode;pNode.next=newNode;returnhead;}// Function to print the doubly linked listfunctionprintList(head){letcurrent=head;while(current!==null){process.stdout.write(current.data.toString());if(current.next!==null)process.stdout.write(" <-> ");current=current.next;}console.log();}// Driver Codelethead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;letp=2,x=6;head=insertAtPos(head,p,x);printList(head);
Output
2 <-> 4 <-> 5 <-> 6
[Expected Approach] Single Traversal - O(n) Time and O(1) Space
The idea is to traverse the doubly linked list until the p-th node is reached. Then create a new node and insert it after the current node by updating the required next and prev pointers.
Working of Approach:
Traverse the list until the p-th node is reached.
Create a new node with value x.
If the current node is the last node, append the new node.
Otherwise, insert the new node between the current node and the next node by updating both next and prev pointers.
Return the head of the modified doubly linked list.
Let us understand with an example: Input: p = 2, x = 6
Traverse the list and stop at the 2nd node, which contains value 5.
Create a new node with value 6.
Since 5 is the last node, connect 5->next to the new node and set 6->prev to 5.
The new node is inserted after the 2nd node while maintaining the doubly linked list links.
Output: 2 <-> 4 <-> 5 <-> 6
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node*prev;Node(intx){data=x;next=prev=nullptr;}};Node*insertAtPos(Node*head,intp,intx){Node*newnode=newNode(x);Node*cur=head;// traverse to the given positionfor(inti=0;i<p;i++)cur=cur->next;if(cur->next==nullptr){cur->next=newnode;newnode->prev=cur;}else{newnode->next=cur->next;cur->next=newnode;newnode->next->prev=newnode;newnode->prev=cur;}returnhead;}// Function to print the doubly linked listvoidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" <-> ";head=head->next;}cout<<endl;}intmain(){// Creating linked list: 2 <-> 4 <-> 5Node*head=newNode(2);head->next=newNode(4);head->next->prev=head;head->next->next=newNode(5);head->next->next->prev=head->next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);return0;}
Java
classNode{publicintdata;publicNodenext;publicNodeprev;publicNode(intx){data=x;next=prev=null;}}publicclassGFG{publicstaticNodeinsertAtPos(Nodehead,intp,intx){Nodenewnode=newNode(x);Nodecur=head;// traverse to the given positionfor(inti=0;i<p;i++)cur=cur.next;if(cur.next==null){cur.next=newnode;newnode.prev=cur;}else{newnode.next=cur.next;cur.next=newnode;newnode.next.prev=newnode;newnode.prev=cur;}returnhead;}// Function to print the doubly linked listpublicstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" <-> ");head=head.next;}System.out.println();}publicstaticvoidmain(String[]args){// Creating linked list: 2 <-> 4 <-> 5Nodehead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);}}
Python
classNode:def__init__(self,x):self.data=xself.next=Noneself.prev=NonedefinsertAtPos(head,p,x):newnode=Node(x)cur=head# traverse to the given positionfor_inrange(p):cur=cur.nextifcur.nextisNone:cur.next=newnodenewnode.prev=curelse:newnode.next=cur.nextcur.next=newnodenewnode.next.prev=newnodenewnode.prev=curreturnhead# Function to print the doubly linked listdefprintList(head):whileheadisnotNone:print(head.data,end="")ifhead.nextisnotNone:print(" <-> ",end="")head=head.nextprint()if__name__=='__main__':# Creating linked list: 2 <-> 4 <-> 5head=Node(2)head.next=Node(4)head.next.prev=headhead.next.next=Node(5)head.next.next.prev=head.nextp=2x=6head=insertAtPos(head,p,x)printList(head)
C#
usingSystem;classNode{publicintdata;publicNodenext;publicNodeprev;publicNode(intx){data=x;next=prev=null;}}classGFG{publicstaticNodeinsertAtPos(Nodehead,intp,intx){Nodenewnode=newNode(x);Nodecur=head;// traverse to the given positionfor(inti=0;i<p;i++)cur=cur.next;if(cur.next==null){cur.next=newnode;newnode.prev=cur;}else{newnode.next=cur.next;cur.next=newnode;newnode.next.prev=newnode;newnode.prev=cur;}returnhead;}// Function to print the doubly linked listpublicstaticvoidprintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" <-> ");head=head.next;}Console.WriteLine();}staticvoidMain(string[]args){// Creating linked list: 2 <-> 4 <-> 5Nodehead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;intp=2,x=6;head=insertAtPos(head,p,x);printList(head);}}
JavaScript
classNode{constructor(x){this.data=x;this.next=null;this.prev=null;}}functioninsertAtPos(head,p,x){letnewnode=newNode(x);letcur=head;// traverse to the given positionfor(leti=0;i<p;i++)cur=cur.next;if(cur.next===null){cur.next=newnode;newnode.prev=cur;}else{newnode.next=cur.next;cur.next=newnode;newnode.next.prev=newnode;newnode.prev=cur;}returnhead;}// Function to print the doubly linked listfunctionprintList(head){letoutput="";while(head!==null){output+=head.data;if(head.next!==null)output+=" <-> ";head=head.next;}console.log(output);}// Driver Codelethead=newNode(2);head.next=newNode(4);head.next.prev=head;head.next.next=newNode(5);head.next.next.prev=head.next;letp=2,x=6;head=insertAtPos(head,p,x);printList(head);