add: 合并两个有序链表

This commit is contained in:
yi-ge 2020-05-01 17:25:01 +08:00
parent ecab5b8850
commit b665d6595e
4 changed files with 73 additions and 3 deletions

View File

@ -271,3 +271,8 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 23. 合并K个排序链表 https://leetcode-cn.com/problems/merge-k-sorted-lists/
- LintCode 104. 合并k个排序链表 https://www.lintcode.com/problem/merge-k-sorted-lists/description
- [合并两个有序链表](src/list/merge-two-sorted-lists.js)
- LeetCode 21. 合并两个有序链表 https://leetcode-cn.com/problems/merge-two-sorted-lists/
- LintCode 165. 合并两个排序链表 https://www.lintcode.com/problem/merge-two-sorted-lists/description

View File

@ -4,8 +4,8 @@
* @param {ListNode[]} right
*/
export const merge = (left, right) => {
const head = {}
let current = head
const dummyHead = {}
let current = dummyHead
while (left !== null && right !== null) {
if (left.val < right.val) {
if (left.val !== null) {
@ -28,7 +28,7 @@ export const merge = (left, right) => {
current.next = left
}
return head.next
return dummyHead.next
}
/**

View File

@ -0,0 +1,42 @@
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
export const mergeTwoLists = function (l1, l2) {
// src/list/merge-k-sorted-lists.js 中已经写过了
const dummyHead = {}
let current = dummyHead
while (l1 !== null && l2 !== null) {
if (l1.val < l2.val) {
if (l1.val !== null) {
current.next = l1
current = current.next
}
l1 = l1.next
} else {
if (l2.val !== null) {
current.next = l2
current = current.next
}
l2 = l2.next
}
}
if (l1 === null) {
current.next = l2
} else {
current.next = l1
}
return dummyHead.next
}

View File

@ -0,0 +1,23 @@
import { mergeTwoLists } from '../../src/list/merge-two-sorted-lists'
function ListNode (val) {
this.val = val
this.next = null
}
const arrToList = (arr) => {
const head = new ListNode(arr[0])
let current = head
for (let n = 1, len = arr.length; n < len; n++) {
current.next = new ListNode(arr[n])
current = current.next
}
return head
}
test('合并两个有序链表', () => {
expect(mergeTwoLists(arrToList([1, 2, 4]), arrToList([1, 3, 4]))).toEqual(arrToList([1, 1, 2, 3, 4, 4]))
expect(mergeTwoLists(arrToList([null]), arrToList([0, 3, 3, null]))).toEqual(arrToList([0, 3, 3, null]))
expect(mergeTwoLists(arrToList([1, 3, 8, 11, 15, null]), arrToList([2, null]))).toEqual(arrToList([1, 2, 3, 8, 11, 15, null]))
})