Leetcode题目21.合并两个有序链表(简单)

题目描述:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

方法一:拼接两个链表

代码实现:

package com.company;

public class Main {

    public static void main(String[] args) {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = null;

        ListNode nodeOne = new ListNode(1);
        ListNode nodeTwo = new ListNode(3);
        ListNode nodeThree = new ListNode(4);
        nodeOne.next = nodeTwo;
        nodeTwo.next = nodeThree;
        nodeThree.next = null;
        System.out.println(mergeTwoLists(node1, nodeOne));
    }

    private static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head;
        //先找到头结点的位置
        if (l1.val <= l2.val) {
            head = l1;
            l1 = l1.next;
        } else {
            head = l2;
            l2 = l2.next;
        }
        //移动指针
        ListNode pNode = head;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                pNode.next = l1;
                l1 = l1.next;
            } else {
                pNode.next = l2;
                l2 = l2.next;
            }
            pNode = pNode.next;
        }
        if (l1 != null) {
            pNode.next = l1;
        }
        if (l2 != null) {
            pNode.next = l2;
        }
        return head;
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

方法二:递归

思路:

思路
标签:链表、递归
这道题可以使用递归实现,新链表也不需要构造新节点,我们下面列举递归三个要素
终止条件:两条链表分别名为 l1 和 l2,当 l1 为空或 l2 为空时结束
返回值:每一层调用都返回排序好的链表头
本级递归内容:如果 l1 的 val 值更小,则将 l1.next 与排序好的链表头相接,l2 同理
O(m+n),m 为 l1的长度,n 为 l2 的长度

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

时间复杂度:O(n + m) 。因为每次循环迭代中,l1 和 l2 只有一个元素会被放进合并链表中, while 循环的次数等于两个链表的总长度。所有其他工作都是常数级别的,所以总的时间复杂度是线性的。

空间复杂度:O(1) 。迭代的过程只会产生几个指针,所以它所需要的空间是常数级别的。

posted @ 2019-10-30 16:59  菜鸟奋斗史  阅读(315)  评论(0编辑  收藏  举报