leetcode_021_Merge_Two_Sorted_Lists

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

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

思路
show me the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 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) {
// 类似归并排序中的合并过程
// 分别创建ListNode类型的 dummyHead 和 cur 待用
ListNode dummyHead = new ListNode(0);
ListNode cur = dummyHead;
// 循环判断:当传入的l1和l2都不是空时进行while循环操作
while(l1 != null && l2 != null){
// 比较l1和l2中的元素大小
if(l1.val < l2.val){
cur.next = l1;
cur = cur.next;
l1 = l1.next;
}else{
cur.next = l2;
cur = cur.next;
l2 = l2.next;
}
}
// 任意一个为空时,直接连接另一条链条
if(l1 == null){
cur.next = l2;
}else{
cur.next = l1;
}
return dummyHead.next;
}
}