var t = -1;
var MAX = 100;
var a = Array(MAX).fill(0);
function isEmpty(x)
{
if(t<0)
{
console.log("Stack
is empty");
}
else
{
console.log("Stack
is not empty");
}
}
function push(x)
{
if(t>=(MAX-1))
{
console.log("Stack Overflow");
return false;
}
else
{
t+=1;
a[t] = x;
console.log(x+" pushed
into stack");
return true;
}
}
function pop(x)
{
if(t<0)
{
console.log("Stack
Underflow");
return 0;
}
else
{
var x = a[t];
t-=1;
console.log(x+" popped
element of the stack");
return x;
}
}
function peek(x)
{
if(t<0)
{
console.log("Stack
Underflow");
return 0;
}
else
{
var x = a[t];
console.log(x+" top
element of stack");
return x;
}
}
function print()
{
for(let i = t
;i>-1;i--)
{
console.log(" "+a[i]);
}
}
console.log("\n\t
STACK OPERATIONS USING ARRAY");
console.log("\n\t--------------------------------");
console.log("\n\t
1.PUSH\n\t 2.POP\n\t 3.TOP element\n\t 4.EMPTY or NOT??\n\t 5.Display\n\t
6.Exit");
var ch;
do
{
var ch = parseInt(prompt("Enter your
choice of operation:"));
switch(ch)
{
case 1:
var x =
parseInt(prompt("Enter a element to be pushed in stack:"));
push(x);
break;
case 2:
console.log("Popped element from stack is:");
pop(x);
break;
case 3:
console.log("Top
element of the stack is:");
peek(x);
break;
case 4:
isEmpty(x);
break;
case 5 :
console.log("Elements of Stack are:");
print();
break;
case 6:
console.log("Thank
You!!!");
break;
default:
console.log("\ninvalid operation ");
}
} while(ch!=6);
Output:-
STACK
OPERATIONS USING ARRAY
--------------------------------
1.PUSH
2.POP
3.TOP element
4.EMPTY or NOT??
5.Display
6.Exit
10 pushed into
stack
20 pushed into
stack
30 pushed into
stack
40 pushed into
stack
50 pushed into
stack
Popped element
from stack is:
50 popped element
of the stack
Top element of
the stack is:
40 top element
of stack
Stack is not
empty
Elements of
Stack are:
40
30
20
10
0 Comments