Quote:
Originally Posted by Entertainment Unit
I like my solution a little better than the book's:
Code:
// Javascript
function isCycle(list) {
var slow,
fast;
slow = fast = list;
while (fast.next) {
slow = slow.next;
fast = fast.next && fast.next.next;
if (slow === fast || fast.next === slow) {
return true;
}
}
return false;
}
Fewer ifs and elses and sometimes while (true) can be a code smell.
|
Ha, except I just realized it doesn't work for lists that have an even number of elements. Better:
Code:
function isCycle(list) {
var slow,
fast;
slow = fast = list;
while (fast.next) {
slow = slow.next;
fast = fast.next && fast.next.next;
if (!fast) {
return false;
}
if (slow === fast || fast.next === slow) {
return true;
}
}
return false;
}
The learning process illustrated!