Node.js examples for Data Structure:List
LinkedList Cycle Check
function Node(value){ this.value = value;//from w w w . j a v a2s.c o m this.next = null; } function SLL(){ this.head = null; this.length = 0; } SLL.prototype.add = function(value){ var node = new Node(value) var current = this.head; if(!current){ this.head = node; this.length++; return node; } while(current.next){ current = current.next; } current.next = node; this.length++; return node; } function hasCycle(list){ var current = list.head; var previous = list.head; while(previous && current && current.next){ previous = previous.next; current = current.next.next; if(previous === current){ return true; } } return false; } var slist = new SLL() slist.add(1) slist.add(2) slist.add(3) slist.add(4) slist.add(5) // console.log(slist) slist.head.next.next.next.next = slist.head.next.next console.log(hasCycle(slist));