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.
NodeSortedInsert(Nodehead,intdata){/* Create Node to insert */NodenewNode=newNode();newNode.data=data;if(head==null){// insert in empty listreturnnewNode;}elseif(data<head.data){// insert in front of listnewNode.next=head;head.prev=newNode;returnnewNode;}else{/* Walk list with 2 pointers */Noden1=null;Noden2=head;while(n2!=null&&n2.data<data){n1=n2;n2=n2.next;}if(n2==null){// insert at end of listn1.next=newNode;newNode.prev=n1;}else{// insert in empty listn1.next=newNode;n2.prev=newNode;newNode.prev=n1;newNode.next=n2;}returnhead;}}
Inserting a Node Into a Sorted Doubly Linked List
You are viewing a single comment's thread. Return to all comments →
Java Iterative solution - passes 100% of test cases
From my HackerRank solutions.
Runtime: O(n)
Space Complexity: O(1)
Let me know if you have any questions.