zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

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

    思路

    递归与非递归。
    时间复杂度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;
        }
    }
    

    笔记

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

  • 相关阅读:
    1008 Elevator
    mysql---时间类型详解
    mysql导入导出
    mysql不能启动报error2013错误的解决办法
    mysql总结
    mysql安装图解
    Access连接数据源配置(新手必知)
    eclipse建包的一些细节
    数据库操作(存着用来复制省的每次写)
    (工具类)MD5算法|时间格式转换|字符串转数字
  • 原文地址:https://www.cnblogs.com/ustca/p/12327272.html
Copyright © 2011-2022 走看看