-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
43 lines (37 loc) · 1.07 KB
/
Copy pathStack.java
File metadata and controls
43 lines (37 loc) · 1.07 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
package project;
public class Stack {
private int[] array;
private int top; // Number of elements
public Stack(int size) {
array = new int[size];
top = 0; // Empty stack has 0 elements
}
public void push(int item) {
if (top < array.length) {
array[top] = item; // Assign to current top index
top = top + 1;
} else {
System.out.println("Stack Overflow");
}
}
public int pop() {
if (top > 0) {
top = top - 1; // Decrement top first
return array[top]; // Return the last element
} else {
System.out.println("Stack Underflow");
return 0; // Default value for underflow
}
}
public int peek() {
if (top > 0) {
return array[top - 1]; // Return the last element without removing
} else {
System.out.println("Stack is empty");
return 0; // Default value for empty stack
}
}
public boolean isEmpty() {
return top == 0;
}
}