In doubly linked list, implement a method to insert a node at specified position and return the list's head. Do nothing if insertion position is outside the bounds of the list.
insertAtPos(1<=>2<=>3,4,2) ==> 1<=>4<=>2<=>3
insertAtPos(1,4,3) ==> 1
next
and prev
pointers properly to fit in this new node in the List
.
1. If the List is empty or the current head node is null
, create a new doubly linked list node and return it as the new head node.
2. Else, maintain two references while traversing, one for tracking the current node and another for tracking the previous node.
3. After traversing to the required spot, insert the new node by re-assigning the references of the current and previous nodes, as well as those of the new node .
4. Return the original head node.
public DoublyLinkedNode insertAtPos(DoublyLinkedNode head, int data, int pos) { }
C
Java
Python