剑指offer25-合并两个有序列表

public class MergeTwoList {
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode result = null;
        // 如果l1和l2有一个为null,返回另一个
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        // 如果l1的值小于l2的值,l1为头节点,开始递归
        if (l1.val < l2.val) {
            result = l1;
            l1.next = mergeTwoLists(l1.next, l2);
        } else {
            result = l2;
            l2.next = mergeTwoLists(l2.next, l1);
        }
        return result;
    }
}
posted @ 2020-10-15 15:45  马晟  阅读(95)  评论(0编辑  收藏  举报