JavaScript 中的反向对象列表

reverse list of objects in JavaScript

我刚通过面试问题:

请反转对象列表。

我的解决方案正确吗? 你会如何分析这个? 是否有更有效的方法来反转单个对象列表?

var node3 = {data: 3, next: null}
var node3 = {data: 2, next: node3}
var node3 = {data: 1, next: node2}

//逻辑上 // node1.next = node2.next = node3.next = null

const function reverse() {
  var node = linkedlist;
  var previous = null;

  while(node) {
        var save = node.next;
        node.next = previous;
        previous = node;
        node = save;
  }
  return previous;   
}

// 用法示例 如果你有一个包含数千个对象的列表怎么办

var myList = node1
myList = reverse(myList)
myList === node3 is true

myList = reverse(myList)
myList === node1 is true

Linked data structure
Linked Lists - Computerphile

var node3 = { data: 3, next: null };
node3 = { data: 2, next: node3 };
node3 = { data: 1, next: node3 }; // <= your code here is node2

// To make it easier to understand I just set the entire LDS directly
// each next is point to next data, null means end of data
let node3 = {
    "data": 1,
    "next": {
        "data": 2,
        "next": {
            "data": 3,
            "next": null
        }
    }
};

function reversLDS(LDS) {
    let newLDS = null; // end of LDS
    while (LDS) { // if not null
        newLDS = {
            data: LDS.data, // read data from LDS
            next: newLDS // set next to previous newLDS(self)
        };
        LDS = LDS.next; // get next LDS
    }
    return newLDS;
}

let reversed = reversLDS(node3);

while (reversed) {
    console.log(reversed);
    reversed = reversed.next;
}

A = 第一 newLDS
B = 第二 newLDS

//↓A                 ↓B
newLDS = { data: LDS.data, next: newLDS };

这里
B还是老newLDS
A 是一个新对象