-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStack1.java
More file actions
92 lines (76 loc) · 1.76 KB
/
Stack1.java
File metadata and controls
92 lines (76 loc) · 1.76 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.*;
public class Stack1 {
int a[], top, n;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack1() throws IOException {
System.out.println("Enter Array Size: ");
n = Integer.parseInt(br.readLine());
a = new int[n];
top = -1;
}
public static void main(String[] args) throws NumberFormatException, IOException {
int option;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Stack1 s = new Stack1();
do {
System.out.println(
"Menu:\n" + " 1. Push\n" + " 2. Pop\n" + " 3. Peek\n" + " 4. Display\n" + " 5. Exit\n");
option = Integer.parseInt(br.readLine());
switch (option) {
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.peek();
break;
case 4:
s.display();
break;
case 5:
System.out.println("Thank you for using this program!");
return;
}
} while (true);
}
void push() throws IOException {
int x;
if (top == n - 1) {
System.out.println("Stack overflow");
} else {
System.out.println("Enter value to be inserted: ");
x = Integer.parseInt(br.readLine());
++top;
a[top] = x;
System.out.println("Value pushed successfully\n");
}
}
void pop() {
if (top == -1) {
System.out.println("Stack underflow");
} else {
System.out.println("Value popped = " + a[top] + "\n");
--top;
}
}
void peek() {
if (top == -1) {
System.out.println("Stack empty");
} else {
System.out.println("Top value = " + a[top] + "\n");
}
}
void display() {
if (top == -1) {
System.out.println("Stack empty");
} else {
System.out.print("Your Current Stack => [ ");
for (int items : a) {
System.out.print(items + " ");
}
System.out.println("]");
}
}
}