题目描述:

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

示例:

输入: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) 。迭代的过程只会产生几个指针,所以它所需要的空间是常数级别的。

最新文章

  1. java script 基础知识
  2. JavaScript正则表达式详解(二)JavaScript中正则表达式函数详解
  3. javascript(js)小数精度丢失的解决方案
  4. Android--ListView下拉刷新
  5. Google Zxing 二维码生成与解析
  6. nova 虚拟机迁移
  7. 【HDU】3506 Monkey Party
  8. Yii源码阅读笔记(二十四)
  9. ASP.NET页面间传值总结
  10. Java程序编译和运行的过程【转】
  11. 关于 hot code replace fail 问题 .
  12. Apache Hadoop 源码阅读
  13. storm出现的背景
  14. All X(思维)
  15. iOS 中 Touch ID得使用方法
  16. Python于*args 和**kwargs使用
  17. 为什么我的会话状态在ASP.NET Core中不工作了?
  18. .a 文件 和 so 文件
  19. Elastic Stack-Elasticsearch使用介绍(一)
  20. WinEdt和LaTeX的简介

热门文章

  1. kali入侵服务器之后清除痕迹
  2. sass之mixin的全局引入(vue3.0)
  3. hbase shell 基本操作
  4. hadoop-hive的内表和外表
  5. 移动端h5+vue失焦搜索,ios和android兼容问题
  6. pandas中Series对象下的str所拥有的方法(df[&quot;xx&quot;].str)
  7. js基本事件
  8. JNetPcap安装及使用
  9. C - Covered Points Count CodeForces - 1000C (差分,离散化,统计)
  10. Almost Regular Bracket Sequence CodeForces - 1095E (线段树,单点更新,区间查询维护括号序列)