这是悦乐书的第148次更新,第150篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第7题(顺位题号是21)。合并两个已排序的链表并将其作为新链表返回。 新链表应该通过拼接前两个链表的节点来完成。例如:

链表L1包含三个节点,为1,2,4

链表L2包含三个节点,为1,3,4

将L1和L2合并后的新链表包含6个节点,为1,1,2,3,4,4

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 此题中的链表是什么?

先来看段代码,下面是定义的ListNode类,有两个属性,一个是存储整数值的val,一个是ListNode类本身的next,存储下一个ListNode的地址值(指针)。形象的解释就是,链表可以是拉链的齿轮,互相咬合;也可以是电影《盗梦空间》中的梦中梦;就像大盒子里面可以继续放盒子一样。

class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}

为了更好的理解链表是怎么存储值的,且看下面的代码。l1的next属性引用了l2,l2的next属性引用了l3。

public class Easy_21_MergeTwoSortedList {

	public static void main(String[] args) {
Easy_21_MergeTwoSortedList instance = new Easy_21_MergeTwoSortedList();
ListNode l1 = new ListNode(1);
ListNode l2 =new ListNode(2);
ListNode l3 =new ListNode(4);
l1.next = l2;
l2.next = l3;
System.out.println(instance.listNodeToString(l1));
ListNode l4 = new ListNode(1);
ListNode l5 =new ListNode(3);
ListNode l6 =new ListNode(4);
l4.next = l5;
l5.next = l6;
System.out.println(instance.listNodeToString(l4));
} public String listNodeToString(ListNode L){
List<Integer> list = new ArrayList<Integer>();
while(L != null){
list.add(L.val);
L = L.next;
}
return list.toString();
}
}

03 第一种解法

因为给的链表都是已经排过序的(由小到大),只需要依次比较两个链表的元素val值即可,并且存入一个新的链表里面。如果某一个链表先循环完,新链表剩下的元素就是另外一个链表剩下的元素。

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = (l1 != null) ? l1 : l2;
return dummy.next;
}

04 第二种解法

像第二种方法循环判断再取值的情况,很容易联想到递归,即自己调用自己,同时给予退出条件即可。使用递归的好处就是代码量少。

public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists2(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists2(l1, l2.next);
return l2;
}
}

05 小结

此题虽然不难,但是需要先将题目意思读懂,并且知道链表是怎么存数据的,这样才能更好解题。为了更好理解,下面贴上全部代码。

package leetcode;

import java.util.ArrayList;
import java.util.List; /**
* 合并两个已排序的链接列表并将其作为新列表返回。 新列表应该通过拼接前两个列表的节点来完成。
* 例:
* 输入:1-> 2-> 4, 1-> 3-> 4
* 输出:1-> 1-> 2-> 3-> 4-> 4
* @author 小川94
* @date 2018-10-21
*/
public class Easy_21_MergeTwoSortedList { public static void main(String[] args) {
Easy_21_MergeTwoSortedList instance = new Easy_21_MergeTwoSortedList();
ListNode l1 = new ListNode(1);
ListNode l2 =new ListNode(2);
ListNode l3 =new ListNode(4);
l1.next = l2;
l2.next = l3;
System.out.println(instance.listNodeToString(l1));
ListNode l4 = new ListNode(1);
ListNode l5 =new ListNode(3);
ListNode l6 =new ListNode(4);
l4.next = l5;
l5.next = l6;
System.out.println(instance.listNodeToString(l4));
ListNode result = instance.mergeTwoLists2(l1, l4);
System.out.println(instance.listNodeToString(result));
} public String listNodeToString(ListNode L){
List<Integer> list = new ArrayList<Integer>();
while(L != null){
list.add(L.val);
L = L.next;
}
return list.toString();
} /**
* 顺位循环判断
* @param l1
* @param l2
* @return
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = (l1 != null) ? l1 : l2;
return dummy.next;
} /**
* 利用递归
* @param l1
* @param l2
* @return
*/
public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
if (l1.val < l2.val) {
l1.next = mergeTwoLists2(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists2(l1, l2.next);
return l2;
}
} } class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}

此题解法远不止上面这两种,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

【算法】LeetCode算法题-Merge Two Sorted List的更多相关文章

  1. 乘风破浪:LeetCode真题_023_Merge k Sorted Lists

    乘风破浪:LeetCode真题_023_Merge k Sorted Lists 一.前言 上次我们学过了合并两个链表,这次我们要合并N个链表要怎么做呢,最先想到的就是转换成2个链表合并的问题,然后解 ...

  2. 乘风破浪:LeetCode真题_021_Merge Two Sorted Lists

    乘风破浪:LeetCode真题_021_Merge Two Sorted Lists 一.前言 关于链表的合并操作我们是非常熟悉的了,下面我们再温故一下将两个有序链表合并成一个的过程,这是基本功. 二 ...

  3. leetcode第22题--Merge k Sorted Lists

    problem:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its compl ...

  4. 【LeetCode练习题】Merge k Sorted Lists

    Merge k Sorted Lists Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

  5. [Leetcode][Python]23: Merge k Sorted Lists

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 23: Merge k Sorted Listshttps://oj.leet ...

  6. 【一天一道LeetCode】#23. Merge k Sorted Lists

    一天一道LeetCode系列 (一)题目 Merge k sorted linked lists and return it as one sorted list. Analyze and descr ...

  7. 【一天一道LeetCode】#21. Merge Two Sorted Lists

    一天一道LeetCode系列 (一)题目 Merge two sorted linked lists and return it as a new list. The new list should ...

  8. 【LeetCode】21. Merge Two Sorted Lists 合并两个有序链表

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:合并,有序链表,递归,迭代,题解,leetcode, 力 ...

  9. 【LeetCode】23. Merge k Sorted Lists 合并K个升序链表

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:合并,链表,单链表,题解,leetcode, 力扣,Py ...

随机推荐

  1. Perl文件句柄相关常量变量

    文件句柄相关变量 对应的官方手册:http://perldoc.perl.org/perlvar.html#Variables-related-to-filehandles 默认情况下: $/:输入行 ...

  2. ElasticSearch+Logstash+Filebeat+Kibana集群日志管理分析平台搭建

    一.ELK搜索引擎原理介绍 在使用搜索引擎是你可能会觉得很简单方便,只需要在搜索栏输入想要的关键字就能显示出想要的结果.但在这简单的操作背后是搜索引擎复杂的逻辑和许多组件协同工作的结果. 搜索引擎的组 ...

  3. Video for Linux Two API Specification

    V4L2 的使用规范,网址为:https://www.linuxtv.org/downloads/legacy/video4linux/API/V4L2_API/spec-single/v4l2.ht ...

  4. UML 用例建模

    用例建模      用例建模的主要功能是表达系统的功能性需求或行为.主要包含用例图和用例描述,其中用例图由参与者.用例.系统边界和箭头组成,用例描述以文本文档的形式详细的描述了用例图中的每个用例.   ...

  5. Python3 系列之 基础语法篇

    基础数据类型 整数 python 可以处理任意大小的整数 浮点数 python 可以处理任意大小的浮点数,但是需要注意的一点是:整数运算永远是精确的(除法也是精确的),而浮点数运算则可能会有四舍五入的 ...

  6. nodemailer + express + h5 拖拽文件上传 实现发送邮件

    一.部署 1.部署Express 2.准备一个邮箱并开始SMTP服务 二.服务器端 三.客户端 四.效果:

  7. canvas-8clip.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. JAVA 多线程(3)

    再讲线程安全: 一.脏读 脏读:在于读字,意在在读取实例变量时,实例变量有可能被另外一个线程更改了,导致获取到的数据出现异常. 在非线程安全的情况下,如果线程A与线程B 共同使用对象实例C中的方法me ...

  9. layui 自定义表单验证的几个实例

    *注:使用本方法请先引入layui依赖的layu.js和layui.css 1.html <input type="text" name="costbudget&q ...

  10. 洛谷P5205 【模板】多项式开根(多项式sqrt)

    题意 题目链接 Sol 这个就很没意思了 求个ln,然后系数除以2,然后exp回去. #include<bits/stdc++.h> #define Pair pair<int, i ...