Question
Using JSFiddle Im trying to do a RPN Stack You will build a Stack Computer from your stack. When a number is entered it goes
Using JSFiddle Im trying to do a RPN Stack
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
So looking above, I got to stack but I need to look like above like when the 2nd digit is enter mine looks like 2 5 not 5 2. The Stack has to be on top or first and I need addition, multiplication, subtraction, and division added.
.HTML:
Javascript + No-Library (pure JS)
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
Step: 1
Get Instant Access with AI-Powered Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started