【问题标题】:Reverse a nested Array list Javascript反转嵌套数组列表Javascript
【发布时间】:2021-01-28 09:29:53
【问题描述】:

我希望它从下到上反转列表。 我使用了 i-- 的 for 循环,但即使使用内置的 Reverse() 函数,我也无法使其工作。

规则是:

  1. 您不能使用内置的 reverse() 函数。
  2. null 是不存在的对象,如果需要,您可以使用空对象。
  3. 您的函数应该能够反转任何类型的值列表。
  4. 您必须至少使用一个数组来解决问题。

原文:

var list = {
   value: 1,
      next: {
         value: 2,
         next: {
            value: 3,
            next: null     
         }
      }
};

将其反转为:

var list = {
   value: 3,
   next: {
     value: 2,
     next: {
       value: 1,
       next: null
     }
   }
};

示例测试用例:

function reverseList(list) {
    // return reversedList;
}

Arguments: { value: 1, next: { value: 2, next: { value: 3, next: null } } };
Returns: { value: 3, next: { value: 2, next: { value: 1, next: null } } };

Arguments: { value: "a", next: { value: "b", next: { value: "c", next: null } } };
Returns: { value: "c", next: { value: "b", next: { value: "a", next: null } } };

【问题讨论】:

  • 幸运的是你不能使用reverse ...因为该数据中绝对没有数组
  • 这被称为反转链表,只是一个编码面试问题,在现实生活中永远不必使用。如果在您编写的某些代码中这是一个真正的问题,那么您使用了错误的数据结构。如果您想在编码面试中寻求帮助,请在此处实现算法(geeksforgeeks.org/reverse-a-linked-list)
  • 谢谢@KyleDePace,是的,这是我被要求解决的问题。你认为它可以很容易地解决吗?也许使用一两个功能?
  • Reverse a nested Array list Javascript 正如 Jaromanda 已经说过的那样,该数据结构中的任何地方都没有数组。那是一个链表。 nested Array list 这个词是从哪里来的? 4. You must use at least one array to solve the problem. 为什么?这是不必要的开销。
  • "这是我被要求解决的问题。" - 然后是面试问题或学校学习任务。无论哪种方式,这都是您研究的任务。我建议您可以先阅读有关 Object.keys()

标签: javascript arrays object properties reverse


【解决方案1】:

没有数组所以你不能内置reverse 函数。还在 SO 上搜索 reverse a linked list 给了我this,我在代码 sn-p 中引用了它。

var reverseLinkedList = function(linkedlist) {
  var node = linkedlist;
  var previous = null;

  while (node) {
    // save next or you lose it!!!
    var save = node.next;
    // reverse pointer
    node.next = previous;
    // increment previous to current node
    previous = node;
    // increment node to next node or null at end of list
    node = save;
  }
  return previous; // Change the list head !!!
}
var list = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: null
    }
  }
};
var linkedlist = reverseLinkedList(list);
console.log(JSON.stringify(linkedlist));

【讨论】:

    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 2012-06-03
    • 2020-01-24
    • 2021-12-06
    • 2010-09-27
    • 2018-12-24
    • 2019-09-22
    • 1970-01-01
    相关资源
    最近更新 更多