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.
Node*SortedInsert(Node*head,intdata){Node*temp=head;//Initializing the new Node Node*newNode=newNode();newNode->data=data;newNode->next=NULL;newNode->prev=NULL;// If thr List is empty point the head to the new node if(temp==NULL){temp=newNode;head=temp;returnhead;}//Check if the data in the new node is bigger// or smaller than each node in the list. if it's// bigger, move to the next node in the list. // If it's the last node stop.while((newNode->data>temp->data)&&temp->next!=NULL){temp=temp->next;}//If it was the last node and the data is still//bigger this new node will be added to the tailif(temp->next==NULL&&newNode->data>temp->data){newNode->prev=temp;temp->next=newNode;returnhead;}//If this was smaller than the node pointed by temp//we add new node before it newNode->prev=temp->prev;temp->prev=newNode;newNode->next=temp;//If there are elements before we need to link its//next to our new nodeif(newNode->prev!=NULL){newNode->prev->next=newNode;}//If there are no elements before it, our node//is the first one so we point the head/temp to itif(newNode->prev==NULL){temp=newNode;returntemp;}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 →
Long commented C++ implementation.