https://leetcode.com/PRoblems/merge-two-sorted-lists/
算法思想: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.
連接兩個排好序(假設升序,降序類似)的鏈表,這是一道典型的遞歸題。比較兩個鏈表的第一個元素,如果l1的第一個node的值要比l2的第一個node的值小,那么新的鏈表的第一個node就是l1的第一個node,第二個node開始就是l1的第二個node和l2連接起來的list;反之同。
程序清單:/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; } else { l2.next = mergeTwoLists(l1, l2.next); return l2; } }}新聞熱點
疑難解答