-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingArray.java
More file actions
69 lines (51 loc) · 1.43 KB
/
StackUsingArray.java
File metadata and controls
69 lines (51 loc) · 1.43 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
package stack.implementation;
import exception.StackIsEmptyException;
import exception.StackIsFullException;
public class StackUsingArray {
private int topIndex;
private int[] stack;
private int capacity;
private int stackSize;
public StackUsingArray(int capacity) {
if (capacity <= 0)
throw new RuntimeException("Stack size must be positive");
this.capacity = capacity;
this.stack = new int[capacity];
this.topIndex = 0;
this.stackSize = 0;
}
// push
public void push(int data) {
if (stackSize == capacity)
throw new StackIsFullException("Stack is full, cannot perfoem push operation");
stack[topIndex] = data;
topIndex++;
stackSize++;
}
// pop
public int pop() {
if (stackSize == 0)
throw new StackIsEmptyException("Unable to pop, Stack is Empty");
int poppedElement = stack[topIndex];
topIndex--;
stackSize--;
return poppedElement;
}
// top
public int top() {
if (stackSize == 0)
throw new StackIsEmptyException("Unable to get top, Stack is Empty");
return stack[topIndex];
}
public int size() {
return stackSize;
}
// isEmpty
public boolean isEmpty() {
return stackSize == 0;
}
// isFull
public boolean isFull() {
return stackSize == capacity;
}
}