Recursion_demo

by davidjb95

HTML

1<p id='output1'></p>
2<p id='output2'></p>
3<p id='output3'></p>
<input type="textbox" id="StackName" Value="3" />

<input type="button" id="AddLink" value="Add to Stack" onClick="addStack();" />

<input type="button" id="Add" value="tower" onClick="recursion();" />

JavaScript

function addStack() {
  var value = document.getElementById("StackName").value;
  var numOfBlocks = parseFloat(value);
  for(i = numOfBlocks; i > 0; i--){
  stack.push(i);
  }
  document.getElementById('output1').innerHTML = 'Add to top of stack ' + stack.toString();
}
function recursion(n, from, to, via) {
  	if (n==0) return;
    
    recursion(n-1, from, via, to);
    moveDisk(from, to);
    
    recursion(n-1, via, to, from);
    }	
      
    document.getElementById('output1').innerHTML = stack.toString();
    document.getElementById('output2').innerHTML = stack2.toString();
    document.getElementById('output3').innerHTML = stack3.toString();
}
var Node = function(_content) {
  this.next = null;
  this.last = null;
  this.content = _content;

}

var Stack = function() {
  this.bottom = null;
  this.top = null;

  this.push = function(_content) {
    // No head - create one
    if (this.bottom == null) {
      this.bottom = new Node(_content);
      this.top = this.bottom;
      return this;
    }
    var addedNode = new Node(_content);
    addedNode.last = this.top; // pointer to previous node
    this.top.next = addedNode; // current top points to new
    this.top = addedNode; // which becomes new top
    return this;
  }

  this.pop = function() {
    if (this.bottom == null) {
      alert("The Stack is Empty");
      return null;
    }

    // Now remove top Node
    var a = this.top; // hold value for return
    this.top = this.top.last;
    this.top.next = null;
    return a;
  }
  this.toString = function() {
    var str = "";
    var node = this.bottom;
    var node2 = this.top;
		var i = 0;
    while (node != null) {
      str += node.content + ":";
      node = node.next;
    }
    return str;
   } 
   
}
var stack = new Stack();
var stack2 = new Stack();
var stack3 = new Stack();
stack.push("O");
stack2.push("O");
stack3.push("O");
document.getElementById('output1').innerHTML = stack.toString();