September 23, 2015
GRK
Problem Statement
You’re given the pointer to the head node of a sorted doubly linked list and an integer to insert into the list. Create a node and insert it into the appropriate position in the list. The head node might be NULL to indicate that the list is empty.
Source Code:
Node* SortedInsert(Node *head,int data)
{
// Complete this function
// Do not write the main method.
Node *temp = new Node;
temp->data = data;
temp->next = NULL;
temp->prev = NULL;
if(head == NULL){
head = temp;
}else{
Node *temp1 = temp;
temp->next = head;
head = temp;
while(temp!= NULL){
temp1 = temp;
temp = temp->next;
if(temp!=NULL){
if(temp1->data>temp->data){
int tdata;
tdata = temp1->data;
temp1->data = temp->data;
temp->data = tdata;
}
}
}
}
return head;
}
Sorry to say ,but i think just swapping the data may not be the optimal solution instead you should have use exchange of pointers method to fulfill ur method.
ReplyDelete