【发布时间】:2015-07-08 20:48:21
【问题描述】:
我试图在 Javascript 中递归地反转 linkedlist。我已经尝试过自己并搜索网络以找到它。但没有成功。下面是我试过的代码:
var Node = (function(){
function Node(val){
this.elem = val;
this.next = null;
}
return Node;
})();
var SLinkedlist = (function(){
function SLinkedlist(){
this.head = new Node("head");
}
return SLinkedlist;
})();
SLinkedlist.prototype.find = function(val){
var current = this.head;
while(current !== null && current.elem !== val){
current = current.next;
}
return current;
}
SLinkedlist.prototype.insert = function(newVal, val){
var current = this.find(val);
var newNode = new Node(newVal);
newNode.next = current.next;
current.next = newNode;
}
function reverseLinkedList(list, previous){
//We need to use the the current setting of
//list.next before we change it. We could save it in a temp variable,
//or, we could call reverseLinkedList recursively
console.log(list);
if(list !== null && list.next !==null){
reverseLinkedList(list.next, list);
}
console.log("after recursion!")
console.log(list);
//Everything after 'list' is now reversed, so we don't need list.next anymore.
//We passed previous in as an argument, so we can go ahead and set next to that.
list.next = previous;
}
reverseLinkedList(list.head, null);
谁能帮帮我?
【问题讨论】:
-
有什么代码可以显示你的进度吗?
-
是的!用代码更新了我的问题。递归方法取自一些例子。
-
@Arpit- 感谢格式化。我是新来的。
标签: javascript recursion data-structures linked-list