Check Cyclic LinkedList – I

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

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

Total
1
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
i-made-a-whole-“game”-with-nextjs

I made a whole “GAME” with NextJs

Next Post
jpa-one-to-one-unidirectional-mapping-example

JPA One To One unidirectional Mapping example

Related Posts