使用javascript反转linkedlist

使用javascript反转linkedlist,javascript,linked-list,Javascript,Linked List,这是一个单链表,我想把它颠倒过来 我在stackoverflow中找到了,但它对我没有帮助 它返回1而不是[16,5,10,1] 我对反向链接列表的了解是 让第一个节点指向null 第二个节点指向第一个节点 第三个节点指向第二个节点 有人能帮我找出如何在我的代码中反转linkedlist吗 这是我的JS: 类链接列表{ 构造函数(值){ 这个头={ 价值:价值, 下一个:空 }; this.tail=this.head; 这个长度=1; } 附加(值){ 常数newNode={ 价值:价值,

这是一个单链表,我想把它颠倒过来

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

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

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

让第一个节点指向null

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

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

有人能帮我找出如何在我的代码中反转linkedlist吗

这是我的JS:

类链接列表{
构造函数(值){
这个头={
价值:价值,
下一个:空
};
this.tail=this.head;
这个长度=1;
}
附加(值){
常数newNode={
价值:价值,
下一个:空
}
this.tail.next=newNode;
this.tail=newNode;
这个.length++;
归还这个;
}
预结束(值){
常数newNode={
价值:价值,
下一个:空
}
newNode.next=this.head;
this.head=newNode;
这个.length++;
归还这个;
}
打印列表(){
常量数组=[];
让currentNode=this.head;
while(currentNode!==null){
array.push(currentNode.value)
currentNode=currentNode.next
}
返回数组;
}
插入(索引、值){
//检查参数是否正确;
如果(索引>=此.length){
console.log('yes')
返回此.append(值);
}
常数newNode={
价值:价值,
下一个:空
}
const leader=this.traverseToIndex(索引-1);
const holdingPointer=leader.next;
leader.next=newNode;
newNode.next=保持指针;
这个.length++;
返回这个.printList();
}
遍历索引(索引){
//检查参数
设计数器=0;
让currentNode=this.head;
while(计数器!==索引){
currentNode=currentNode.next;
计数器++;
}
返回当前节点;
}
删除(索引){
//检查参数
const leader=this.traverseToIndex(索引-1);
const unwantedNode=leader.next;
leader.next=unwantedNode.next;
这个长度--;
返回这个.printList();
}
反向{
让currentNode=this.head;
var-previous=null;
while(当前节点){
//保存下一个,否则将丢失它!!!
var save=currentNode.next;
//反向指针
currentNode.next=上一个;
//当前节点之前的增量
前一个=当前节点;
//将节点递增到下一个节点或在列表末尾为null
currentNode=保存;
}
返回这个.printList()
}
}
让myLinkedList=newLinkedList(10);
myLinkedList.append(5)
myLinkedList.append(16)
myLinkedList.prepend(1)
myLinkedList.insert(2,99)
myLinkedList.remove(2)

myLinkedList.reverse()//应该返回[16,5,10,1]
在循环重新设置头部和尾部后,实际上已经非常接近了:

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

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

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

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

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

看来你没领会我的意思。我已经在我的类中有了一个反向函数。只是不要创建一个新的。让我再检查一遍,就像你没有领会我的意思一样。我的类中已经有了一个反向函数。只是不要创建一个新的。让我再次检查