美文网首页
021,Merge Two Sorted Lists

021,Merge Two Sorted Lists

作者: 丹之 | 来源:发表于2018-10-08 08:31 被阅读0次

https://leetcode.com/problems/merge-two-sorted-lists/discuss/9713/A-recursive-solution

合并有序的链表

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

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;
    }
    }
}

个人理解:递归求解链表。

想象有两个两个链表,

每次递归求解一次小的节点。

相关文章

网友评论

      本文标题:021,Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/lakdaftx.html