Node.js examples for Data Structure:List
find Middle in singly linked list
function Node (val){ this.data = val;/* ww w. j a v a 2 s . 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 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 detectMiddle(sll){ var walker = sll.head; var runner = sll.head; while(walker && runner && runner.next){ walker = walker.next; runner = runner.next.next; } return walker; } var sList = new SLL(); sList.add(1) sList.add(2) sList.add(3) sList.add(4) var stringify = JSON.stringify(sList) var middle = detectMiddle(sList) console.log(middle)