题目描述(easy)

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

基础解法

在做本题的过程中,由于本人链表这块儿不是很熟悉,所以仿照了Discuss里的解法。思路如下,链表1和链表2是两个

代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1==null)
{
return l2;
}
if(l2==null)
{
return l1;
} if(l1.val<=l2.val)
{
ListNode newNode = new ListNode(l1.val);
newNode.next = mergeTwoLists(l1.next,l2);
return newNode; }
else
{
ListNode newNode = new ListNode(l2.val);
newNode.next = mergeTwoLists(l1,l2.next);
return newNode; } }
}

在解决该题目的过程中,大家容易犯的错误有:一是在合并的过程可能出现中断,另一个是存在特殊值的判断问题。

我们分析合并两个链表时,都是从头节点开始。如果链表1的头节点小于链表2的头节点,则链表1的头节点将是合并后链表的头节点。接下来我们继续开始下一轮合并。在两个链表中依然是排序的,因此合并这两个链表的步骤和前面的是一样的。我们还是比较两个头节点的值。如果链表2的头节点小于链表1的头节点的值,因此链表2的头节点的值将是合并剩余节点得到的链表的头节点。

由上图我们可以看到,(a)链表1的头节点的值小于链表2的头节点的值,因此链表1的头节点是合并后链表的头节点。(b)在剩余的节点中,链表2的头节点的值小于链表1的头节点的值,因此链表2的头节点是生育节点的头节点,把这个节点和之前已经合并好的链表的尾节点链接起来。

因此这是一个递归的过程,而递归的停止条件是,当输入第一个的链表为空时,我们只需要返回另外一个链表即可,让它和第二个链表合并。而当输入的第二个链表的为空时,我们只需要返回另外第一个链表即可。

代码优化

我们可以看到,在循环判断的内部,

ListNode newNode = new ListNode(l1.val);
newNode.next = mergeTwoLists(l1.next,l2);

这步的目的是使用一个新的节点来完成链表合并。在该步中,我们让newNode节点等于l1节点的值,实际上我们并不需要再额外创建一个节点等于l1,只需要让原来的l1节点当作头节点即可。省去了每次new新节点的所花的空间。

链表介绍

链表也是线性结构,但是和数组不同,链表中的数据并不存储在连续的内存值中。元素通过指针连接在一起。

链表的优势:

  • 动态大小
  • 容易删增

劣势:

  • 不允许随机访问,只允许顺序访问
  • 需要额外的内存来存储指针

表示方法:

链表由指向链表第一个节点的指针表示。链表的节点叫头节点。如果链表为空,则头也为空。

每个节点包含两部分:数据和指针。

public class LinkedList
{
Node head;
class Node
{
int data;
Node next;
Node(int d)
{
data = d;
} } }

第一个简单的java语言链表,

代码如下:

public class LinkedList
{
Node head; static class Node
{
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
} public static void main(String[] args)
{
LinkedList llist = new LinkedList(); llist.head = new Node(1);
Node second = new Node(2);
Node third = new Node(3); llist.head.next = second;
second.next = third; } }

其中,Node head是用来声明一个链表的头节点;在class Node 中,声明链表的结构,一个数据data, 一个下一个节点。并声明一个初始化构造器。

在主函数中,我们创建一个链表。并用

  • llist.head = new Node(1);创建第一个节点;
  • Node second = new Node(2);创建第二个节点并将数据赋值为2;
  • Node third = new Node(3);用来创建第三个节点,并将数据赋值为3;

接下来开始连接不同的节点:

  • llist.head.next = second连接第一个和第二个节点;

  • second.next = second连接第二个和第三个节点;

链表遍历:

public class LinkedList
{
Node head; static class Node
{
int data;
Node next; Node(int d)
{
data = d;
next = null;
} } public static void main(String[] args)
{
LinkedList llist = new LinkedList(); llist.head = new Node(1); Node second = new Node(2); Node third = new Node(3); llist.head.next = second; second.next = third; llist.printLinkedList(); } public void printLinkedList()
{
Node n = head; while(n!=null)
{
System.out.println(n.data);
n = n.next;
}
}
}

其中在链表中,n = head表示指向head的节点。再通过while循环来便利内容打印

Leetcode练习题21. Merge Two Sorted Lists的更多相关文章

  1. [Leetcode][Python]21: Merge Two Sorted Lists

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 21: Merge Two Sorted Listshttps://oj.le ...

  2. C# 写 LeetCode easy #21 Merge Two Sorted Lists

    21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list s ...

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

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

  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】#21. Merge Two Sorted Lists

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

  6. LeetCode 【21. Merge Two Sorted Lists】

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t ...

  7. 【LeetCode】21. Merge Two Sorted Lists

    题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splici ...

  8. 【leetcode】 21. Merge Two Sorted Lists

    题目描述: Merge two sorted linked lists and return it as a new list. The new list should be made by spli ...

  9. LeetCode:21. Merge Two Sorted Lists(Easy)

    1. 原题链接 https://leetcode.com/problems/merge-two-sorted-lists/description/ 2. 题目要求 给出两个已经从小到大排序的链表ls1 ...

随机推荐

  1. XML JS Demo

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  2. solr设置分片和副本

    numShards:分片数 replicationFactor:每个分片下的副本数 maxShardsPerNode:当numShards为1,replicationFactor为3时,maxShar ...

  3. PostgreSQL的同步级别与MySQL的半同步after_sync比较

    MySQL的半同步中通过binlog进行流复制,同步级别和PostgreSQL对比可以发现: PostgreSQL                MySQL off local            ...

  4. Oracle sqlplus prelim 参数介绍

    SQL>conn / as sysdba ORA-00020: maximum number of processes (xxxx) exceeded 报错解决方法 解决 ORA-00020 错 ...

  5. Redis安全策略

    1. 开启redis密码认证,并设置高复杂度密码 描述 redis在redis.conf配置文件中,设置配置项requirepass, 开户密码认证. redis因查询效率高,auth这种命令每秒能处 ...

  6. 客户端相关知识学习(五)之什么是webView

    webview是什么?作用是什么?和浏览器有什么关系? Android系统中内置了一款高性能 webkit 内核浏览器,在 SDK 中封装为一个叫做 WebView 组件也就是说WebView是一个基 ...

  7. pytorch中torch.narrow()函数

    torch.narrow(input, dim, start, length) → Tensor Returns a new tensor that is a narrowed version of  ...

  8. typeof,instanceof的区别,扩展知识:显示原型(prototype)与隐式类型(__protot__)

    3.typeof 和instanceof区别 1.typeof 主要用于判断对象类型 console.log(typeof null) //object console.log(typeof unde ...

  9. php+ajax远程加载避免重复提交

    近日在练习签到送积分功能时,发现可以在一瞬间的时候提交好多次 导致可以重复领取多次积分 除了增加请求限制之外 发现ajax提交没有限制重复提交 遂立此贴为警示 首先上表单代码 <form ons ...

  10. Spring中配置Hibernate事务管理

    <!-- transationManager --> <bean id="transactionManager" class="org.springfr ...