【问题标题】:Efficiently sorting linked list in Javascript?在Javascript中有效地对链表进行排序?
【发布时间】:2020-04-16 10:26:00
【问题描述】:

在 Javascript/NodeJS 中对链表进行排序的最有效方法是什么?如果我有一个带有idcomesAfter 的对象数组,它们指的是列表中上一项的id,我该如何排列?

解决方案中的 ES6 功能很好用。它不应该修改原始数组,而是返回一个新数组。 (但如果不难展示如何在适当的位置进行操作,那也有助于查看。)

// before sorting
[
  { id: "three", comesAfter: "two" },
  { id: "one", comesAfter: null },
  { id: "four", comesAfter: "three" },
  { id: "two", comesAfter: "one" },
]

// after sorting
[
  { id: "one", comesAfter: null },
  { id: "two", comesAfter: "one" },
  { id: "three", comesAfter: "two" },
  { id: "four", comesAfter: "three" },
]

【问题讨论】:

    标签: javascript ecmascript-6 linked-list


    【解决方案1】:

    创建一个对象似乎是合理的,像这样:

    var obj = {};
    for (var i = 0; i < input.length; i++) {
        obj[input[i].comesAfter] = input[i];
    }
    

    现在,让我们生成输出:

    var index = 0;
    var output = [obj.null];
    while (++index < input.length) {
        output[index] = obj[output[index - 1].id];
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-14
      • 2010-09-14
      • 2023-03-20
      • 2010-10-20
      • 2012-08-02
      • 2012-10-07
      • 1970-01-01
      相关资源
      最近更新 更多