-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCode4.java
More file actions
52 lines (45 loc) · 1.18 KB
/
Code4.java
File metadata and controls
52 lines (45 loc) · 1.18 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
import java.util.EmptyStackException;
class Stack {
private int maxSize;
private int[] stackArray;
private int top;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (top == maxSize - 1) {
System.out.println("Stack is full. Cannot push element.");
return;
}
stackArray[++top] = value;
}
public void pop() {
if (top == -1) {
throw new EmptyStackException();
}
System.out.println("Popped Element is: " + stackArray[top--]);
maxSize--;
}
public void peek() {
if (top == -1) {
throw new EmptyStackException();
}
System.out.println("Stack Top is: " + stackArray[top]);
}
}
public class Code4 {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(50);
stack.push(40);
stack.push(30);
stack.push(20);
stack.push(10);
stack.peek();
stack.pop();
stack.pop();
stack.peek();
}
}