You are viewing a single comment's thread. Return to all comments →
static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { List<SinglyLinkedListNode> list1 = linkedLinkToList(head1); List<SinglyLinkedListNode> list2 = linkedLinkToList(head2); List<SinglyLinkedListNode> combined = new ArrayList<SinglyLinkedListNode>(); combined.addAll(list1); combined.addAll(list2); //sort Collections.sort(combined, (a,b)->{ return a.data - b.data; }); // re-link for(int i = 0; i < combined.size()-1; i++){ combined.get(i).next = combined.get(i+1); } // combined.get(combined.size() - 1).next = null; return combined.get(0); } static List<SinglyLinkedListNode> linkedLinkToList(SinglyLinkedListNode head){ ArrayList<SinglyLinkedListNode> result = new ArrayList<SinglyLinkedListNode>(); SinglyLinkedListNode current = head; do{ result.add(current); current = current.next; }while(current != null); return result; }
Seems like cookies are disabled on this browser, please enable them to open this website
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →