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

    笔记

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

  • 相关阅读:
    Shiro【常用的自定义】
    Shiro【重要概念总结】
    Shiro【自定义Realm实战】
    Shiro【内置Realm实操】
    Shiro【快速上手】
    Shiro【初识】
    面向对象【抽象类和接口的区别】
    面向对象【多态中的成员访问特点】
    Kafka2.12-2.5.0在windows环境的安装 启动 通信测试
    CentOS.iso 下载地址收纳整理
  • 原文地址:https://www.cnblogs.com/ustca/p/12327272.html
Copyright © 2011-2022 走看看