LInklist - reverse not working.

// javascript Linkelist code. // creating class: function Node() { this.head = { val: null, next:null }; } Node.prototype.add = function(newEle) { // create a new node first. var newNode = new Node(); newNode.val = newEle; newNode.next = null; // checking head. if(this.head.val == null) { //console.log("assigning " + newEle + " as head."); this.head= newNode; }else { var runner = this.head; while(runner.next) { runner= runner.next; } runner.next= newNode; // console.log("new Element attached.."); } }; Node.prototype.show = function() { var runn = this.head; while(runn.next) { console.log(runn.val + "->"); runn= runn.next; } console.log(runn.val+ "."); }; // remove a node from singly linklist. Node.prototype.remove = function(arg) { var slow= this.head; var fast = this.head; var flag=null; // checkinf if alleast 2 elements exist or not. if(slow.next.val) { console.log("atleast 2 node exist.."); fast = fast.next; // moving one step ahed. if(slow.val == arg){ this.head = fast; //slow= null; return; } flag=1; }else { if(slow.val == arg) { cosole.log("This is head node which you want to delete.. "); this.head = null; }else { console.log("Element entered not part of the linklist .."); return; } } // while(fast.next) { if(fast.val == arg) { slow.next = fast.next; fast = null; return; }else { fast = fast.next; slow= slow.next; } // console.log(fast.next); } console.log(fast.next+ "element not found.."); return; }; //--------------------- Node.prototype.fastAdd = function(newEle) { console.log("adding in O(n)"); var newNode = new Node(); newNode.val=newEle; newNode.next=this.head; // moving head behind. this.head = newNode; }; // reversing linklist; Node.prototype.reverse = function(linklist) { var runner = linklist.head; var stack =[]; //var runner = this.head; while(runner.next) { stack.push(runner); runner = runner.next; } console.log('stack.length:' + stack.length); var revHead=null; var traveller = revHead; var dummyobj; while(stack.length) { traveller = revHead; if(!revHead) { revHead=stack.pop(); console.log("revHead: " + revHead.val); revHead.next= null; } while(traveller.next) { traveller = traveller.next; } traveller.next = stack.pop(); } /* if(!revHead) { console.log("--llllll-----"+ dummyobj.val +" "+ dummyobj.next); revHead = dummyobj; //revHead.next = null; } while (runner.next) { runner= runner.next; } runner.next = dummyobj; */ }; // ------------------------------------------------- var myLinklist = new Node(); myLinklist.add(3); myLinklist.add(6); myLinklist.add(9); myLinklist.add(92); myLinklist.add(93); myLinklist.add(94); //myLinklist.fastAdd(100); myLinklist.reverse(myLinklist); //myLinklist.show(); //myLinklist.remove(94); //myLinklist.show(); //------------------------------------------------------

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.