題目鏈接:https://leetcode-cn.com/problems/merge-two-sorted-lists/
將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
歸併排序中排序那一部分的代碼即可,解題和模板如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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(l2.next, l1);
return l2;
}
}
}