stack_example
by davidjb95
HTML
<p id='output1'></p>
<p id='output2'></p>
<input type="textbox" id="StackName" Value="Put in number or operator" />
<input type="button" id="AddLink" value="Add to Stack" onClick="addStack();" />
JavaScript
function addStack() {
var value = document.getElementById("StackName").value;
stack.push(value);
document.getElementById('output1').innerHTML = 'Add to top of stack ' + stack.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;
}
// Case of one node
if (this.bottom == this.top) {
// Exercise for students to implement
alert("You must implement this case");
return this.top;
}
// 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 operator = new Array('/','*','-','+');
var i = 0;
// sees if top content is one of the operators
for(i=0;i < operator.length; i++){
if(node2.content == "/"){
alert("it works");
}
}
var test = parseInt(node2.content);
// if the input is not a number don't accept it
if(Number.isNaN(test)){
stack.pop();
}
document.getElementById('output2').innerHTML = test + test;
while (node != null) {
str += node.content + ":";
node = node.next;
}
return str;
}
}
// Create a Linked List and Add Nodes
var stack = new...