-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.java
More file actions
48 lines (41 loc) · 970 Bytes
/
ArrayStack.java
File metadata and controls
48 lines (41 loc) · 970 Bytes
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
import java.lang.reflect.Array;
import java.util.EmptyStackException;
public class ArrayStack<T> implements Stack<T> {
T[] arr;
int top;
int size = 10;
public ArrayStack() {
T[] temp = (T[]) new Object[size];
arr = temp;
top = -1;
}
public boolean empty() {
return top == -1;
}
public T pop() {
if(empty()) {
throw new EmptyStackException();
}
return arr[top--];
}
public T peek() {
if(empty()) {
throw new EmptyStackException();
}
return arr[top];
}
public void push(T t) {
if(top == arr.length - 1) {
growArray();
}
arr[++top] = t;
}
protected void growArray() {
T[] temp = (T[]) new Object[arr.length * 2];
size = (arr.length * 2)-1;
for(int i = 0; i < arr.length; i++) {
temp[i] = arr[i];
}
arr = temp;
}
}