1
+ import java .io .*;
2
+ import java .util .*;
3
+ class StackArray {
4
+
5
+ Scanner sc = new Scanner (System .in );
6
+ static int st [];
7
+ static int top =-1 ;
8
+
9
+ public static void main (String args [])throws IOException {
10
+
11
+ StackArray stack = new StackArray ();
12
+ int n = stack .Input (1 );
13
+ if (n ==-1 ) return ;
14
+ stack .CreateStack (n );
15
+ boolean INTR =true ;
16
+ do {
17
+ int choice = stack .StackMenu ();
18
+ switch (choice ){
19
+ case (1 ):
20
+ {
21
+ if (!stack .StackOverflow ()){
22
+ System .out .print ("PUSH: " );
23
+ int element = stack .Input (0 );
24
+ stack .Push (element );
25
+ System .out .println (element +" has been pushed into stack" );
26
+ }
27
+ else
28
+ System .out .println ("Stack is full" );
29
+ break ;
30
+ }
31
+ case (2 ):
32
+ {
33
+ if (!stack .StackUnderflow ()){
34
+ int elem = stack .Pop ();
35
+ System .out .println ("Popped element: " +elem );
36
+ }
37
+ else
38
+ System .out .println ("Stack is empty" );
39
+ break ;
40
+ }
41
+ case (3 ):
42
+ {
43
+ if (!stack .StackUnderflow ())
44
+ System .out .println ("Top element is: " +st [top ]);
45
+ else
46
+ System .out .println ("Stack is empty" );
47
+ break ;
48
+ }
49
+ case (4 ):
50
+ {
51
+ System .out .println ("Size of Stack is " +(top +1 ));
52
+ break ;
53
+ }
54
+ case (5 ):
55
+ {
56
+ if (!stack .StackUnderflow ())
57
+ stack .Display ();
58
+ else
59
+ System .out .println ("Stack is empty" );
60
+ break ;
61
+ }
62
+ case (0 ):
63
+ INTR =false ;
64
+
65
+ }
66
+ if (choice >5 ||choice <0 )
67
+ System .out .println ("Not a valid menu option" );
68
+
69
+ }while (INTR );
70
+ }
71
+
72
+ public int Input (int flag ){
73
+ if (flag ==1 ){
74
+ System .out .print ("Enter the size of the stack: " );
75
+ int n = sc .nextInt ();
76
+ if (n <=0 ){
77
+ System .out .println ("Zero stack size. Exiting..." );
78
+ return -1 ;
79
+ }
80
+ return n ;
81
+ }
82
+ else
83
+ return sc .nextInt ();
84
+ }
85
+
86
+ public void CreateStack (int n ){
87
+ st = new int [n ];
88
+ }
89
+
90
+ public int StackMenu (){
91
+ System .out .println ("STACK OPTIONS: " );
92
+ System .out .println ("1.PUSH 2.POP 3.PEEK 4.SIZE 5.DISPLAY 0.EXIT" );
93
+ return sc .nextInt ();
94
+ }
95
+
96
+ public void Push (int elem ){
97
+ top ++;
98
+ st [top ]=elem ;
99
+ }
100
+ public int Pop (){
101
+ --top ;
102
+ return st [top +1 ];
103
+ }
104
+ public void Display (){
105
+ for (int i =0 ;i <=top ;i ++)
106
+ System .out .print (st [i ]+" " );
107
+ System .out .println ();
108
+ }
109
+ public boolean StackOverflow (){
110
+ if (top ==(st .length -1 ))
111
+ return true ;
112
+ else
113
+ return false ;
114
+ }
115
+ public boolean StackUnderflow (){
116
+ if (top ==-1 )
117
+ return true ;
118
+ else
119
+ return false ;
120
+ }
121
+
122
+ }
0 commit comments