Given a linked list, determine if it has a cycle in it - Node.js Data Structure

Node.js examples for Data Structure:List

Description

Given a linked list, determine if it has a cycle in it

Demo Code


// Given a linked list, determine if it has a cycle in it.

function Node (val){
    this.data = val;//from   w  w  w  .j  a v a  2  s. c  om
    this.next = null;
}
function SLL (){
    this.head = null;
    this.length = 0;
}
SLL.prototype.add = function(value){
    var node = new Node(value);
    var currentNode = this.head;
    if(!currentNode){
        this.head = node;
        this.length++;
        return node;
    }
    while(currentNode.next){
        currentNode = currentNode.next;
    }
    currentNode.next = node;
    this.length++;
    return node;
}
function detectLoop(sll){
    var walker = sll.head;
    var runner = sll.head;
    while(walker && runner && runner.next){
        walker = walker.next;
        runner = runner.next.next;
        if(walker === runner){
            return true;
        }
    }
    return false;
}

function findLoopStart(sll){
    var walker = sll.head;
    var runner = sll.head;
    while(walker && runner){
        walker = walker.next
        if(!runner.next){
            return null;
        }
        runner = runner.next.next;
        if(walker === runner){
            walker = sll.head;
            while(walker != runner){
                walker = walker.next;
                runner = runner.next;
            }
            return walker;
        }
    }
}

var SinglyLinkedList = new SLL()
SinglyLinkedList.add(1)
SinglyLinkedList.add(2)
SinglyLinkedList.add(3)
SinglyLinkedList.add(4)
SinglyLinkedList.add(5)

console.log(detectLoop(SinglyLinkedList));

SinglyLinkedList.head.next.next.next.next = SinglyLinkedList.head.next.next

console.log(detectLoop(SinglyLinkedList));
console.log(findLoopStart(SinglyLinkedList));

Related Tutorials