zoukankan      html  css  js  c++  java
• # 图解算法——合并两个有序的列表（Merge Two Sorted Lists）

## 1. 题目描述

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

## 2.示例

示例1：

```Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]```

示例2：

```Input: l1 = [], l2 = []
Output: []```

示例3：

```Input: l1 = [], l2 = [0]
Output: [0]```

## 3. 要求

• The number of nodes in both lists is in the range `[0, 50]`.
• `-100 <= Node.val <= 100`
• Both `l1` and `l2` are sorted in non-decreasing order.

## 4.解题思想

```/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {
//非递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
while(l1 != null && l2!=null){
//res.val = l1.val>l2.val?l2.val:l1.val;
if(l1.val>=l2.val){
//res.val = l2.val;
res.next = l1;//是res.next而不是赋值操作.val　　　　　　　　　　l2 = l2.next;
}else if(l1.val<l2.val){
//res.val = l1.val;
res.next = l2;　　　　　　　　　　l1 = l1.next;
}
res = res.next;
}

if(l1 != null){
res.next = l1;//这里是res.next，不是res
}
if(l2 != null){
res.next = l2;//这里是res.next，不是res
}
}

//递归
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;
}

}
}```

Over......

• 相关阅读:
实验2实验报告
实验1实验报告
汇编实验九
汇编实验5
汇编实验四
汇编实验三
汇编实验二
汇编实验一
汇编第一章
浅谈webpack4.0 性能优化
• 原文地址：https://www.cnblogs.com/gjmhome/p/14412308.html