describe
Determine whether there is a cycle in the given linked list. Returns true if there is a ring, false otherwise.
Data range: the length of the linked list is 0≤ n ≤ ≤10000, and the value of any node in the linked list satisfies |val| <= 100000
Requirements: space complexity O(1), time complexity O(n)
The input is divided into two parts, the first part is a linked list, the second part represents whether there is a ring, and then the composed head node is passed into the function. -1 means no loop, other numbers mean loop, these parameter explanations are just for the convenience of readers to self-test and debug. What is actually read in during programming is the head node of the linked list.
For example, when {3,2,0,-4},1 is input, the corresponding linked list structure is shown in the figure below:
It can be seen that the entry node of the ring is the first node from the head node (note: the head node is the 0th node), so the output is true.
Example 1
enter:
{3,2,0,-4},1
return value:
true
illustrate:
The first part {3,2,0,-4} represents a linked list, and the 1 in the second part means, -4 to position 1 (note: the head node is position 0), that is, there is a link between -4->2, consisting of The incoming head is a linked list with rings, return true
Example 2
enter:
{1},-1
return value:
false
Copy instructions:
The first part {1} represents a linked list, -1 represents acyclic, and the incoming head is composed of an acyclic singly linked list, returning false
Example 3
enter:
{-1,-7,7,-4,19,6,-9,-5,-2,-5},6
return value:
true
Idea: In fact, this topic looks very complicated, but it is actually very tasteless. In fact, it has already connected the linked list for you behind it. You only need to judge whether you have traversed this node, so set a flag value for the traversed node, and traverse, as long as the flag value is gone. It means that it has been visited before, and it will return true. After traversing, it is undefined and it will return false.
Full code:
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
function hasCycle( head ) {
// write code here
while(head) {
if(head.flag===undefined) {
head.flag=1;
}
else {
return true;
}
head=head.next;
}
return false;
}
module.exports = {
hasCycle : hasCycle
};