首页 > 编程语言 > 详细

合并两个排序的链表

时间:2020-02-18 19:17:01      阅读:43      评论:0      收藏:0      [点我收藏+]

题目描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路

递归与非递归。
时间复杂度O(m+n),空间复杂度O(m+n)。

递归代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null)    return list2;
        if(list2 == null)    return list1;
        ListNode curr = null;
        if(list1.val < list2.val) {
            curr = list1;
            curr.next = Merge(list1.next, list2);
        } else {
            curr = list2;
            curr.next = Merge(list1, list2.next);
        }
        return curr;
    }
}

非递归代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null)    return list2;
        if(list2 == null)    return list1;
        ListNode head = null;
        ListNode curr = null;
        if(list1.val < list2.val) {
            head = list1;
            list1 = list1.next;
        } else {
            head = list2;
            list2 = list2.next;
        }
        curr = head;
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                curr.next = list1;
                list1 = list1.next;
            } else {
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }
        if(list1 != null) {
            curr.next = list1;
        }
        if(list2 != null) {
            curr.next = list2;
        }
        return head;
    }
}

笔记

提交时递归运行速度更快。

合并两个排序的链表

原文:https://www.cnblogs.com/ustca/p/12327272.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!