Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is a JSFiddle Assignment so this needs to be written at jsfiddle.net with t

ID: 3923237 • Letter: T

Question

This is a JSFiddle Assignment so this needs to be written at jsfiddle.net with the HTML and Java scriptincluded

Implement a Stack in Javascript. 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..

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

6 [enter] 6

2 [enter] 2 6

* [enter] * 2 6 -> collapses to 12

would leave at 12 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.

Explanation / Answer

Since we are restricted from using an Array, we'll use the DOM itself to store the values and make it work like a stack.


HTML
<input type='text' id='val'/>
<input type='button' value='Submit'/>
<br/>
Current Stack:&nbsp;
<div id='CurrentStack'>
</div>

JAVASCRIPT
function fun() {
       var data = document.getElementById("val").value;
updateCurrentStack(data);
}
function updateCurrentStack(data){
       switch(data){
case '+':
   pushToStack(parseInt(popFromStack()) + parseInt(popFromStack()));
   break;
case '-':
   pushToStack(parseInt(popFromStack()) - parseInt(popFromStack()));
   break;
case '*':
   pushToStack(parseInt(popFromStack()) * parseInt(popFromStack()));
   break;
case '/':
   pushToStack(parseInt(popFromStack()) / parseInt(popFromStack()));
   break;
default:
           pushToStack(data);
}
}
function pushToStack(data){
   document.getElementById("CurrentStack").innerHTML += data + " ";
document.getElementById("val").value = "";
}
function popFromStack(){
   var stack = document.getElementById("CurrentStack").innerHTML;
document.getElementById("CurrentStack").innerHTML = "";
var res = stack.split(" ");
for(var i=0;i<res.length-2;i++)
   document.getElementById("CurrentStack").innerHTML += res[i] + " ";
document.getElementById("val").value = "";
return res[res.length-2];
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote