gpt4 book ai didi

javascript - 使用 javascript 反转链表

转载 作者:行者123 更新时间:2023-12-01 01:12:48 25 4
gpt4 key购买 nike

这是一个单链表,我想反转它

我找到了this在 stackoverflow 中,但这对我没有帮助

它返回 1 而不是 [16,5,10,1]

我对反向链接列表的了解是

让第一个节点指向null

第二个节点指向第一个节点

第三个节点指向第二个节点

有人可以帮我弄清楚如何反转代码中的链表吗?

这是我的 JS:

class LinkedList {
constructor(value) {
this.head = {
value: value,
next: null
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = {
value: value,
next: null
}
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = {
value: value,
next: null
}
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
printList() {
const array = [];
let currentNode = this.head;
while (currentNode !== null) {
array.push(currentNode.value)
currentNode = currentNode.next
}
return array;
}
insert(index, value) {
//Check for proper parameters;
if (index >= this.length) {
console.log('yes')
return this.append(value);
}

const newNode = {
value: value,
next: null
}
const leader = this.traverseToIndex(index - 1);
const holdingPointer = leader.next;
leader.next = newNode;
newNode.next = holdingPointer;
this.length++;
return this.printList();
}
traverseToIndex(index) {
//Check parameters
let counter = 0;
let currentNode = this.head;
while (counter !== index) {
currentNode = currentNode.next;
counter++;
}
return currentNode;
}
remove(index) {
// Check Parameters
const leader = this.traverseToIndex(index - 1);
const unwantedNode = leader.next;
leader.next = unwantedNode.next;
this.length--;
return this.printList();
}
reverse() {
let currentNode = this.head;
var previous = null;

while (currentNode) {
// save next or you lose it!!!
var save = currentNode.next;
// reverse pointer
currentNode.next = previous;
// increment previous to current node
previous = currentNode;
// increment node to next node or null at end of list
currentNode = save;
}
return this.printList()
}
}

let myLinkedList = new LinkedList(10);
myLinkedList.append(5)
myLinkedList.append(16)
myLinkedList.prepend(1)
myLinkedList.insert(2, 99)
myLinkedList.remove(2)
myLinkedList.reverse() //should return [16,5,10,1]

最佳答案

你实际上已经非常接近了,在循环之后只需重新设置头部和尾部:

 while(/*...*/ { /*...*/ }

this.tail = this.head;
this.head = previous;

关于javascript - 使用 javascript 反转链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55016688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com