Leetcode 21 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.

题目要求咱们将两个有序链表合成一个有序的链表。node

Example:
输入: 1->2->4, 1->3->4
输出: 1->1->2->3->4->4指针

想法

  • 首先要判断其中一个链表为空的状态,这种状况直接返回另外一个链表便可。
  • 每次递归都会得到当前两个链表指针位置的值较小的节点,从而组成一个新的链表。

解法

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        
        ListNode mergeHead;
        if(l1.val < l2.val){
            mergeHead = l1;
            mergeHead.next = mergeTwoLists(l1.next, l2);
        }
        else{
            mergeHead = l2;
            mergeHead.next = mergeTwoLists(l1, l2.next);
        }
        return mergeHead;
    }
}
相关文章
相关标签/搜索