# 数据结构与算法 | Leetcode 21:Merge Two Sorted Lists

bicycle_journey-wallpaper

## 有序链表合并

Leetcode 21:Merge Two Sorted Lists

### 示例

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

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyNode = new ListNode(0);
ListNode tail = dummyNode;

while(true){

if(l1 == null){
tail.next = l2;
break;
}

if(l2 == null){
tail.next = l1;
break;
}

ListNode next1 = l1;
ListNode next2 = l2;

if(next1.val <= next2.val){
tail.next = next1;
l1 = l1.next;
}else{
tail.next = next2;
l2 = l2.next;
}

tail = tail.next;
}

return dummyNode.next;

}

}
``````

### 递归

#### 代码

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

ListNode result = null;

if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}

if(l1.val <= l2.val){
result = l1;
result.next = mergeTwoLists(l1.next, l2);
}else{
result = l2;
result.next = mergeTwoLists(l1, l2.next);
}
return result;
}

}
``````