xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 合并两个有序链表算法题解 All In One

LeetCode 合并两个有序链表算法题解 All In One

js / ts 实现合并链表

合并链表原理 图解

比较两个链表的节点值大小,递归处理


function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  if(!list1) {
     return list2;
  }
  if(!list2) {
     return list1;
  }
  if(list1.val < list2.val) {
    // 递归 子问题
    list1.next = mergeTwoLists(list1.next, list2);
    return list1;
  } else {
    list2.next = mergeTwoLists(list1, list2.next);
    return list2;
  }
};


  1. 合并两个有序链表
// 21. Merge Two Sorted Lists

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2022-08-28
 * @modified
 *
 * @description 21. Merge Two Sorted Lists
 * @description 21. 合并两个有序链表
 * @difficulty Easy
 * @ime_complexity O(n)
 * @space_complexity O(n)
 * @augments
 * @example
 * @link https://leetcode.com/problems/merge-two-sorted-lists/
 * @link https://leetcode-cn.com/problems/merge-two-sorted-lists/
 * @solutions
 *
 * @best_solutions
 *
 */

// export {};

const log = console.log;

// singly-linked list
class ListNode {
  val: number
  next: ListNode | null
  constructor(val?: number, next?: ListNode | null) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
  }
  // add
  // remove
}


function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
  if(!list1) {
     return list2;
  }
  if(!list2) {
     return list1;
  }
  if(list1.val < list2.val) {
    // 递归 子问题
    list1.next = mergeTwoLists(list1.next, list2);
    return list1;
  } else {
    list2.next = mergeTwoLists(list1, list2.next);
    return list2;
  }
};


 /*

 test cases

 [1,2,4]
 [1,3,4]
 []
 []
 []
 [0]

 */


function LinkedListGenerator(arr: number[]) {
  let head;
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    if(i === 0) {
      head = new ListNode(arr[len - 1 - i], null);
    } else {
      let temp = new ListNode(arr[len - 1 - i], null);
      temp.next = head;
      head = temp;
    }
  }
  // console.log(head);
  return head;
}


// 测试用例 test cases
const testCases = [
  {
    inputs: [[1,2,4], [1,3,4]],
    result: [1,1,2,3,4,4],
    desc: 'value equal to [1,1,2,3,4,4]',
  },
  {
    inputs: [[], []],
    result: [],
    desc: 'value equal to []',
  },
  {
    inputs: [[], [0]],
    result: [0],
    desc: 'value equal to [0]',
  },
];

for (const [i, testCase] of testCases.entries()) {
  const [first, second] = testCase.inputs;
  const list1: ListNode | null = LinkedListGenerator(first);
  const list2: ListNode | null = LinkedListGenerator(second);
  const result = mergeTwoLists(list1, list2);
  const testResult = LinkedListGenerator(testCase.result);
  log(`test case i result: `, JSON.stringify(result) === JSON.stringify(testResult) ? `✅ passed` : `❌ failed`, JSON.stringify(testResult));
  // log(`test case i result: `, result === testCase.result ? `passed ✅` : `failed ❌`, result);
  // log(`test case i =`, testCase);
}



/*

$ npx ts-node ./021\ merge-two-sorted-lists.ts

*/

https://leetcode.com/problems/merge-two-sorted-lists/
https://leetcode.cn/problems/merge-two-sorted-lists/

LeetCode 题解 / LeetCode Solutions

https://www.youtube.com/results?search_query=+Leetcode+21

https://www.youtube.com/playlist?list=PLamwFu9yMruCBtS2tHUD77oI_Wsce-syE

YouTube & LeetCode 力扣官方算法题解视频列表

https://github.com/xgqfrms/leetcode/issues/14

https://www.youtube.com/channel/UCftIXZeipv4MTVwmfFphtYw/videos

https://neetcode.io/

https://github.com/neetcode-gh/leetcode/blob/main/javascript/21-Merge-Two-Sorted-Lists.js

https://github.com/neetcode-gh/leetcode/blob/main/typescript/21-Merge-Two-Sorted-Lists.ts

类似问题

LeetCode 206. Reverse Linked List / 反转链表

https://leetcode.com/problems/reverse-linked-list/

LeetCode 92. Reverse Linked List II / 反转链表 2

https://leetcode.com/problems/reverse-linked-list-ii/

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-08-28 17:13  xgqfrms  阅读(28)  评论(2编辑  收藏  举报