題目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
思路:
合併兩個鏈結串列(單向),並且回傳排序好之結果.
由於是屬於單向鏈結串列,在合併排序過程較為複雜
所以首先可以先透過標準的排序函式先將資料進行排序後在將資料重新串接回單向鏈結串列後回傳.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { List<Integer> list = sort(l1,l2); ListNode res = null; for (int i : list){ ListNode node = new ListNode(i); node.next = res; res = node; } return res; } private static List<Integer> sort(ListNode l1, ListNode l2){ List<Integer> list = new LinkedList<Integer>(); while(l1!=null){ list.add(l1.val); l1 = l1.next; } while(l2!=null){ list.add(l2.val); l2 = l2.next; } Collections.sort(list,Collections.reverseOrder()); return list; } |
文章標籤
全站熱搜