Approach 1
Where we are using Temp pointer.
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
var hasCycle = function(head) {
let tempNode = new ListNode(0);
let current = head;
while(current){
if(current.next === tempNode){
return true;
}
let saveNext = current.next;
current.next = tempNode;
current = saveNext;
}
return false;
};
Approach 2
Using Map (or can be done using set) to keep track of visited pointers
var hasCycle = function(head) {
let mapValues = new Map();
while (head) {
if (mapValues.has(head)) {
return true;
} else {
mapValues.set(head, "Yes");
head = head.next;
}
}
return false;
};
Approach 3
Where you can modify the way of creating Node by using additional pointer -(Visited = false(default)) & can traverse list.
if visited is true -> return true else false