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.
Nicely done, used some what same logic in C++ , but didn't work. Then used your as a reference and implemented in C++. Worked nicely. Thanks.
Implementation in C++ similar to yours.
/* Insert Node in a doubly sorted linked list After each insertion, the list should be sorted Node is defined as struct Node { int data; Node *next; Node *prev; }*/Node*SortedInsert(Node*head,intdata){// Complete this function// Do not write the main method. structNode*new_node=newNode();structNode*temp=head;new_node->data=data;//case when List is emptyif(head==NULL){head=new_node;returnhead;}//insertion at beginning of Listelseif(data<temp->data){new_node->next=temp;temp->prev=new_node;head=new_node;returnhead;}//walking with 2 pointerselse{structNode*temp1=NULL;//traversing only if new_node has larger datawhile(temp!=NULL&&temp->data<data){temp1=temp;//temp1 is node previous to temptemp=temp->next;}//insertion at end of LLif(temp==NULL){temp1->next=new_node;new_node->prev=temp1;new_node->next=NULL;}//insertion in between//temp1 is node prev to temp//temp is ahead of temp1//new_node has to be inserted between temp and temp1else{temp1->next=new_node;temp->prev=new_node;new_node->next=temp;new_node->prev=temp1;}returnhead;}}
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 →
Nicely done, used some what same logic in C++ , but didn't work. Then used your as a reference and implemented in C++. Worked nicely. Thanks.
Implementation in C++ similar to yours.