-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingArray.java
More file actions
59 lines (48 loc) · 1.21 KB
/
StackUsingArray.java
File metadata and controls
59 lines (48 loc) · 1.21 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
package stack;
public class StackUsingArray implements CustomStackInterface {
private final int[] arr;
private final int capacity;
private int idx;
public StackUsingArray(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
idx = -1;
}
@Override
public int push(int element) throws StackOverflowError {
if (idx == capacity - 1) throw new StackOverflowError("Stack size exceeds");
idx++;
arr[idx] = element;
return arr.length;
}
@Override
public int pop() throws Exception {
if (idx == -1) throw new Exception("Stack is Empty");
int ans = arr[idx];
idx--;
return ans;
}
@Override
public int peak() throws Exception {
if (idx == 1) throw new Exception("Stack is Empty");
return arr[idx];
}
@Override
public boolean isEmpty() {
return idx == -1;
}
@Override
public int size() {
return idx + 1;
}
@Override
public boolean isFull() {
return !isEmpty();
}
@Override
public void printStack() {
for (int i = 0; i <= idx; i++) {
System.out.println(arr[idx]);
}
}
}