DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Updated on

Detect Cycle LinkedList - I

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;
};

Enter fullscreen mode Exit fullscreen mode

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;

};
Enter fullscreen mode Exit fullscreen mode

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

Approach 4 :

Using slow & fast pointer

var hasCycle = function(head) {
    let slow = head;
    let fast =  head;
    while(fast !== null && fast.next !== null){
        slow = slow?.next;
        fast = fast?.next?.next;

         if(slow == fast){
            return true;
        }
    }
    return false;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jjenus profile image
JJenus

The second approach can detect a circle at any point. Sweet.

But the first seems like a circle itself as each iteration assign next to same tempNode and then take the value from save, making the assignment irrelevant.