We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Solution below in Java. The author probably wanted position paramaters exceeding the List size to be added to the end of the List.
NodeInsertNth(Nodehead,intdata,intposition){//Will Need to Return Head Node NodetrackedHeadNode=head;NodenodeToInsert=newNode();nodeToInsert.data=data;//Empty List - Returned newly created node or nullif(head==null){returnnodeToInsert;}//Inserting a Node ahead of the Listif(position==0){nodeToInsert.next=head;returnnodeToInsert;}//Traverse the Singly Linked List to 1 Position Prior//Stop traversing if you reached the end of the ListintcurrPosition=0;while(currPosition<position-1&&head.next!=null){head=head.next;currPosition++;}//Inserting a Node in-between a List or at the end of of a ListNodenodeAtPosition=head.next;head.next=nodeToInsert;head=head.next;head.next=nodeAtPosition;returntrackedHeadNode;}
Insert a node at a specific position in a linked list
You are viewing a single comment's thread. Return to all comments →
Solution below in Java. The author probably wanted position paramaters exceeding the List size to be added to the end of the List.