forked from Ritikraja07/Java-problem-Open-Source
-
Notifications
You must be signed in to change notification settings - Fork 1
/
StackUsingArray.java
71 lines (59 loc) · 1.78 KB
/
StackUsingArray.java
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
public class StackUsingArray {
private int maxSize;
private int top;
private int[] stackArray;
public StackUsingArray(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("Stack is full. Cannot push " + value);
} else {
stackArray[++top] = value;
System.out.println("Pushed " + value + " onto the stack");
}
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot pop.");
return -1;
} else {
int poppedValue = stackArray[top--];
System.out.println("Popped " + poppedValue + " from the stack");
return poppedValue;
}
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty. Cannot peek.");
return -1;
} else {
return stackArray[top];
}
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public int size() {
return top + 1;
}
public static void main(String[] args) {
StackUsingArray stack = new StackUsingArray(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack size: " + stack.size());
System.out.println("Top element: " + stack.peek());
stack.pop();
System.out.println("Popped. New top element: " + stack.peek());
stack.pop();
stack.pop();
stack.pop();
System.out.println("Is stack empty? " + stack.isEmpty());
}
}