Node.js examples for Data Structure:List
find Node From End of singly linked list
function Node(val){ this.data = val;/*from w w w.j a v a 2 s . co 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 findNodeFromEnd(sll,k){ var node = sll.head; var i = 1; var kthNode; if(k <= 0){ return; } while(node){ if(i === k){ kthNode = sll.head; } else if(i-k > 0){ kthNode = kthNode.next; } i++; node = node.next; } return kthNode; } var linkedlist = new SLL(); linkedlist.add(1) linkedlist.add(2); linkedlist.add(3) linkedlist.add(4) linkedlist.add(5) console.log(findNodeFromEnd(linkedlist,1))