Given a list, the list is determined whether a ring. (Do not use extra space)
Example: abcb
Ideas:
1. Method pointer speed
Set two hands, fast hands each take two steps slow pointer each time step, if it is a ring, then the pointer will soon overtake slower pointer until the pointer is equal to the fast and slow pointer when it returns true. Otherwise it returns false
var hasCycle = function (head) {
// 1. Analyzing the absence of
IF (! head || head.next) {
return to false
}
// 2. double pointer loop
var FAST = head.next
var SLOW = head
// 2.1 fast pointer each take two steps, each step by slow pointer, if the pointer has been a fast value, it proved to be the ring until the two are equal, exit
the while (the fAST && fast.next) {
IF (the fAST == sLOW ) {
return to true
}
FAST = fast.next.next
SLOW =slow.next
}
//2.2 Otherwise, it is not annular
return to false
};
2. I do not know what method
var hasCycle = function(head) {
while(head != null){
if(head == head.next){
return true;
}
if(head.next != null){
head.next = head.next.next;
}
head = head.next;
}
return false;
};
This approach will destroy the list and is not recommended