Question: Implement a Stack in Javascript (you will turn in a link to your program in JSFiddle). Do not use an array as the stack or

Implement a Stack in Javascript (you will turn in a link to your program in JSFiddle). Do not use an array as the stack or in the implementation of the stack. Repeat You MUST implement the Stack (start with your linked list) without the use of an array..

You will build a Stack Computer from your stack. When a number is entered it goes onto the top of the stack. When an operation is entered, the previous 2 numbers are operated on by the operation and the result is pushed onto the top of the stack. This is how an RPN calculator.

For example

2 [enter] 2

5 [enter] 5 2

* [enter] * 5 2 -> collapses to 10

would leave at 10 at the top of the stack.

The program should use a simple input box, either a text field or prompt and display the contents of the Stack.

Contents of Stack:

Here's my code, I just need help making it work in jsfiddle!

HTML

Contents of stack:

Javascript

var Node = function(_content) { this.next = null; this.last = null; this.content = _content; }; var Stack = function() { this.top = null; this.bottom = null; this.push = function(_content) { if (this.bottom == null) { this.bottom = new Node(_content); this.top = this.bottom; return this; } var addedNode = new Node(_content); addedNode.last = this.top; this.top.next = addedNode; this.top = addedNode; }; this.pop = function() { if (this.bottom == null) { alert("The stack is empty"); return null; } if (this.bottom == this.top) { this.top = this.bottom; this.top.last = null; return this.top; } 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; while (node != null) { str += node.content + ", "; node = node.next; } return str; }; };

function clearDisplay() { var d = ""; document.getElementById("value").value = ""; } var stack = new Stack(); var a; var b; var c; var result; var input;

function push() //added push function { input = document.getElementById("value").value; if (input === "" || input === " ") { alert("Please enter a number"); } stack.push(input); document.getElementById('output').innerHTML = stack.toString(); clearDisplay(); if (input == '+') { var a = stack.pop(); var b = stack.pop(); stack.push(a + b); document.getElementById('output').innerHTML = stack.toString(); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!