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.
My Java solution with linear time complexity and constant space complexity:
publicstaticDoublyLinkedListNodesortedInsert(DoublyLinkedListNodellist,intdata){//if llist is null, set it to a new node w/ dataif(llist==null)returnllist=newDoublyLinkedListNode(data);//init a new node w/ dataDoublyLinkedListNodenewNode=newDoublyLinkedListNode(data);DoublyLinkedListNodecurr=llist;//if the first node's data is >= than new node's dataif(data<=llist.data){newNode.next=llist;llist.prev=newNode;returnnewNode;}//iterate thru llistwhile(curr!=null){//if curr data is <= curr and next data is > curr or null, insert new nodeif(curr.data<=data&&(curr.next==null||curr.next.data>data)){newNode.next=curr.next;newNode.prev=curr;if(curr.next!=null)curr.next.prev=newNode;curr.next=newNode;break;}curr=curr.next;}//return llistreturnllist;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Inserting a Node Into a Sorted Doubly Linked List
You are viewing a single comment's thread. Return to all comments →
My Java solution with linear time complexity and constant space complexity: