Java program that implements stack ADT

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
class stack<E>
{
private final int size;
private int top;
private E[] elements;
public stack()
{
this(10);
}
public stack(int s)
{
size=s>0?s:10;
top=-1;
elements=(E[])new Object[size];
}
public void push(E x)
{
if(top==size-1)
System.out.println("Overflow");
elements[++top]=x;
}
public E pop()
{
if(top==-1)
System.out.println("Underflow");
return elements[top--]; 
}
public void display()
{
if(top==-1)
System.out.println("Stack is empty");
else
{
for(int i=0;i<top;i++)
System.out.println(elements[i]);
}
}
}
 
public class stacktest
{
public static void main(String[] args)
{
int ch,ch1;
stack<Double>d_stack;
d_stack=new stack<Double>(5);
Scanner input=new Scanner(System.in);
do
{
System.out.println("Menu is as follows:");
System.out.println("1.Push\n2.Pop\n3.Display\n4.Exit");
System.out.println("Enter your choice:");
ch=input.nextInt();
switch(ch)
{
case 1:	System.out.println("Enter element to push:");
double item=input.nextInt();
d_stack.push(item);
break;
case 2:	double item1=d_stack.pop();
System.out.println("Popped item:"+item1);
break;
case 3:	d_stack.display();
break;
default:	break;
}
}while(ch!=4);		
}
}

Output:
Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter element to push :12

Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter element to push:13

Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
12.0
13.0

Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
Popped item:13.0

Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
Popped item:12.0

Menu is as follows:
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
Stack is empty

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in