This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by ZeeshanAli-0704
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
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by ZeeshanAli-0704
ZeeshanAli-0704 | Sciencx (2022-09-07T02:55:12+00:00) Check Cyclic LinkedList – I. Retrieved from https://www.scien.cx/2022/09/07/check-cyclic-linkedlist-i/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.