LeetCode-21. Merge Two Sorted Lists

问题描述

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

Constraints:

  • 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.

解答

方法一:递归法
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
/**
* @Description: 合并两个有序链表
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
* @Description: 递归法
*/
const mergeTwoLists = function (l1, l2) {
if (l1 === null) {
return l2
} else if (l2 === null) {
return l1
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists2(l1.next, l2)
return l1
} else {
l2.next = mergeTwoLists2(l1, l2.next)
return l2
}
}
方法二:迭代法
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
37
38
39
/**
* @Description: 合并两个有序链表
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
* @Description: 迭代法
*/
const mergeTwoLists = function (l1, l2) {
if (l1 === null) {
return l2
} else if (l2 === null) {
return l1
const listHead = new ListNode()
let preNode = listHead

while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
preNode.next = l1
l1 = l1.next
} else {
preNode.next = l2
l2 = l2.next
}
preNode = preNode.next
}
preNode.next = (l1 === null) ? l2 : l1
return listHead.next
}