-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathStacks.java
More file actions
71 lines (60 loc) · 1.75 KB
/
Copy pathStacks.java
File metadata and controls
71 lines (60 loc) · 1.75 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
70
71
package Lists;
public class Stacks<T> {
private Object[] arr;
private int top = -1;
private final int DEFAULT_CAPACITY = 5;
private boolean expand = false;
public Stacks() {
// this creates a dynamic stack with no length bound
arr = new Object[DEFAULT_CAPACITY];
expand = true;
}
public Stacks(int capacity) {
// this creates capacity bounded stack
arr = new Object[capacity];
}
private void doubleArr() {
// this method used internally for dynamic length of stack
Object[] temp = new Object[2 * arr.length];
for (int i = 0; i < arr.length; i++)
temp[i] = arr[i];
arr = temp;
}
public T push(T val) throws RuntimeException {
if (top == arr.length - 1) {
if (expand) doubleArr();
else throw new RuntimeException("Stack Overflow");
}
arr[++top] = val;
return (T) arr[top];
}
public boolean isEmpty() {
return top == -1;
}
public int size() {
return this.top + 1;
}
public T peek() throws RuntimeException {
if (top == -1) throw new RuntimeException("Empty stack exception");
return (T) arr[top];
}
public T pop() throws RuntimeException {
if (top == -1) throw new RuntimeException("Empty stack exception");
T temp = (T) arr[top--];
return temp;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder("[");
int i = 0;
for (; i < top; i++) {
ret.append(arr[i] + ",");
}
if (arr[i] != null) {
ret.append(arr[i] + "]");
} else {
ret.append("]");
}
return ret.toString();
}
}