Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:21. 合并两个有序链表,利用数组排序,JavaScript,详细注释 #124

Open
chencl1986 opened this issue Aug 8, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/

解题思路:

  1. 将两个链表的节点都push到数组中。
  2. 利用数组的sort方法,对数组进行排序。
  3. 将排序后的节点依次取出,存储为新链表。
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function (l1, l2) {
  // 创建一个伪节点,排序后的新链表的首节点会存储在dummyNode.next中
  let dummyNode = new ListNode(-1);
  // 存储新链表的节点,会随着新链表的连接而重新赋值
  // 新链表的首节点存储为dummyNode,避免在存储新链表时,首节点为空的问题
  let newListNode = dummyNode;
  // 用数组存储新链表的每个节点,同时提供排序功能
  let nodeArr = [];

  // 同时遍历两个旧链表,并将每个节点存储到数组中
  while (l1 || l2) {
    if (l1) {
      nodeArr.push(l1);
      l1 = l1.next;
    }
    if (l2) {
      nodeArr.push(l2);
      l2 = l2.next;
    }
  }

  // 对数组中的链表节点进行排序
  nodeArr.sort((a, b) => a.val - b.val);

  // 将排序好的各个节点连接成新链表
  for (let i = 0; i < nodeArr.length; i++) {
    // 将每个节点保存在新链表中。
    newListNode.next = nodeArr[i];
    newListNode = newListNode.next;
  }

  // dummyNode.next指向的是新链表的第一个节点
  // 因此此处返回的就是新链表。
  return dummyNode.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant