GeeksforGeeks » Interview Questions
Amazon Interview Question for Software Engineer/Developer (0 - 2 Years)
(4 posts)-
1 > Sort the doubly linked list with out swaping the values
-
Merge Sort can be easily implemented for doubly linked list. It will be similar to http://www.geeksforgeeks.org/archives/7740
-
Use merge sort technique.
struct node *merge(struct node *head1,struct node* head2,struct node *result) { if(!head1) return head2; if(!head2) return head1; if(head1->data <= head2->data) { result=head1; result->next=merge(head1->next,head2,result); } else { result=head2; result->next=merge(head1,head2->next,result); } return result; } struct node* MergeSort(struct node **start) { struct node *fastPtr=*start,*slowPtr=*start,*head2=NULL,*result; if(!*start || !((*start)->next)) return *start; while(fastPtr->next && fastPtr->next->next) { fastPtr=fastPtr->next->next; slowPtr=slowPtr->next; } head2=slowPtr->next; slowPtr->next=NULL; *start=MergeSort(start); head2=MergeSort(&head2); return merge(*start,head2,result); } -
Insertion sort technique can also be applied .As double linked list is given,a node can be inserted at proper place by moving back.
Reply
You must log in to post.