Domanda di colloquio di Amazon

Merge two sorted linked lists with unique integers.

Risposte di colloquio

Anonimo

14 feb 2012

public void Merge(LinkList list1, LinkList list2) { if (list1.head == null && list2.head == null) { System.out.println("Empty list"); //checks if list is empty } if (list1.head == null) { list2.printList(); } if (list2.head == null) { list1.printList(); } LinkList list3 = new LinkList(); Node a = list1.head; Node b = list2.head; while (a != null && b != null) { if (a.value b.value) { list3.insert(b.value); b = b.next; } else if (a.value == b.value){ //inserts only unique value to the merged list list3.insert(a.value); a = a.next; b = b.next; } } if (a == null) { while (b != null) { list3.insert(b.value); b = b.next; } } if (b == null) { while (a != null) { list3.insert(a.value); a = a.next; } } list3.printList(); }

2

Anonimo

9 feb 2012

Maintain two pointers, one for each list. Loop until atleast one of the two pointers is null, while adding the smaller of the two pointer values to the resulting linked list. Once one of the two pointers is null, add the remaining elements of the other pointer to the resulting linked list. Return the list.