【剑指Offer】面试题25:合并两个排序的链表

本文介绍了如何将两个单调递增的链表合并为一个,保持结果链表依然单调不减。提供了两种解法,分别是递归和迭代。递归解法的时间复杂度为O(m+n),空间复杂度为O(m+n),而迭代解法同样具有O(m+n)的时间复杂度,但空间复杂度降低到O(1)。示例中展示了具体实现过程,并用示例数据{1,3,5}

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * 面试题25:合并两个排序的链表
 * 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
 * 输入:{1,3,5},{2,4,6},输出{1,2,3,4,5,6}
 * @author dengjie
 * @create 2021-03-23 18:16
 */
public class Solution25 {
    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(3);
        Node node3 = new Node(5);
        Node node4 = new Node(2);
        Node node5 = new Node(4);
        Node node6 = new Node(6);
        node1.next = node2;
        node2.next = node3;

        node4.next = node5;
        node5.next = node6;
        Node res = mergeIteration(node1,node4);
        System.out.println(res);
    }

    /**
     * 递归写法,时间复杂度O(m+n),空间复杂度O(m+n)
     * @param list1
     * @param list2
     * @return
     */
    public static Node merge(Node list1, Node list2){
        if (list1 == null){
            return list2;
        }
        if (list2 == null){
            return list1;
        }

        Node newNode = null;
        if (list1.val < list2.val){
            newNode = list1;
            newNode.next = merge(list1.next,list2);
        }else {
            newNode = list2;
            newNode.next = merge(list1, list2.next);
        }
        return newNode;
    }

    /**
     * 迭代写法,时间复杂度O(m+n),空间复杂度O(1)
     * @param list1
     * @param list2
     * @return
     */
    public static Node mergeIteration(Node list1, Node list2){
        if (list1 == null){
            return list2;
        }
        if (list2 == null){
            return list1;
        }

        Node newNode = new Node(0);
        Node cur = newNode;
        while (list1 != null && list2 != null){
            if (list1.val < list2.val){
                cur.next = list1;
                list1 = list1.next;
            }else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if (list1 == null){
            cur.next = list2;
        }else {
            cur.next = list1;
        }
        return newNode.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值