- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathStack.java
More file actions
Latest commit
100 lines (89 loc) · 2.74 KB
/
Copy pathStack.java
File metadata and controls
100 lines (89 loc) · 2.74 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
93
94
95
96
97
98
99
100
importExceptions.OverflowException;
importExceptions.UnderflowException;
importjava.util.Scanner;
publicclassStack {
privateint[] stack;
privateintsize, top;
Stack() {
stack = null;
size = 0;
top = -1;
}
Stack(intsize) {
this.size = size;
top = -1;
stack = newint[size];
}
publicstaticvoidmain(String[] args) {
intch, x;
Scannersc = newScanner(System.in);
System.out.print("Enter the size of the stack : ");
intn = sc.nextInt();
Stacks = newStack(n);
loop:
for (; ; ) {
System.out.print("1. Push\n" +
"2. Pop\n" +
"3. Display\n" +
"0. Exit\n" +
"Enter your choice : ");
ch = sc.nextInt();
switch (ch) {
case0:
breakloop;
case1:
System.out.print("Enter the number you want to push : ");
x = sc.nextInt();
try {
s.push(x);
} catch (OverflowExceptione) {
System.out.println(e.getMessage());
}
break;
case2:
try {
x = s.pop();
System.out.println(x + " has been popped");
} catch (UnderflowExceptione) {
System.out.println(e.getMessage());
}
break;
case3:
s.display();
break;
default:
System.out.println("Dude, seriously?\nI'm sure you can do better than that.\nTry again.");
}
System.out.println();
}
}
privatebooleanisFull() {
returntop >= size - 1;
}
privatebooleanisEmpty() {
returntop == -1;
}
privatevoidpush(intx) throwsOverflowException {
if (!isFull())
stack[++top] = x;
else
thrownewOverflowException("Stack is full");
}
privateintpop() throwsUnderflowException {
if (!isEmpty())
returnstack[top--];
else
thrownewUnderflowException("Stack is empty");
}
privatevoiddisplay() {
if (isEmpty()) {
System.out.println("[]");
return;
}
inti;
System.out.print("[");
for (i = 0; i < top; i++)
System.out.print(stack[i] + ", ");
System.out.println(stack[i] + "]");
}
}