【发布时间】:2016-07-19 01:20:54
【问题描述】:
如果起始节点正确传递给函数,我的解决方案会很好。我想知道我的解决方案是否良好且有效。如果循环通过第一个节点作为参数传递给的函数存在,我应该能够返回 true。我想知道我的解决方案是否有效,尤其是对于面试环境。我在代码中的 cmets 是不言自明的。我使用变量 track 遍历列表并检查 null 或 head 作为下一个。如果我遇到其中任何一个遍历结束,然后单独检查 null 或 head 条件,并基于此返回适当的布尔值。
function SLLNode(elem) {
this.value=elem;
this.next=null;
}
var hasCycle=function(node){
var track=node;
//traverse thru list till next node is either null or back to first node
while(track.next!==null && track.next!==this.head){
track=track.next;
}
if(track.next === null){ //if next node null then no cycle
return false;
}
if(track.next===this.head){ //if next node head then there is cycle
return true;
}
}
var my_node1=new SLLNode(3);
var my_node2=new SLLNode(5);
var my_node3=new SLLNode(19);
//assigning head
var head=my_node1;
//connecting linked list
my_node1.next=my_node2;
my_node2.next=my_node3;
my_node3.next=my_node1; //cycle
console.log("Has cycle?: "+hasCycle(my_node1)); //outputs true as expected
var node1=new SLLNode(3);
var node2=new SLLNode(5);
var node3=new SLLNode(19);
//assigning head
var head1=node1;
node1.next=node2;
node2.next=node3;
console.log("Has cycle?: "+hasCycle(node1)); //outputs false as expected
【问题讨论】: