Amazon Interview Question

how to merge two sorted linklist?

Interview Answers

Anonymous

Oct 27, 2012

You don't need merge sort here. This is a O(n) task, because the lists are already sorted. In fact, this merge routine is part of merge sort. No sorting takes place here, only merging, and it could be done in linear time. Node* merge(Node* list1, Node* list2) { Node* merged = null; Node** tail = &merged; while (list1 && list2) { if (list1->data data) { *tail = list1; list1 = list1->next; } else { *tail = list2; list2 = list2->next; } tail = &((*tail)->next); } *tail = list1 ? list1 : list2; return merged; }

1

Anonymous

Oct 10, 2011

Use MergeSort.