-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyResizingArrayStack.java
71 lines (56 loc) · 1.55 KB
/
MyResizingArrayStack.java
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
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
import java.util.Iterator;
public class MyResizingArrayStack<T> implements Iterable<T> {
private T[] items;
private int n;
private void resize(int max) {
T[] arr = (T[]) new Object[max];
for (int i = 0; i < n; i++) {
arr[i] = items[i];
}
items = arr;
}
public MyResizingArrayStack(int capacity) {
n = capacity;
items = (T[]) new Object[1];
}
public void push(T item) {
if (n == items.length)
resize(2 * n);
items[n++] = item;
}
public T pop() {
T result = items[--n];
items[n] = null;
if (n == items.length / 4 && n > 0)
resize(n / 2);
return result;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
private class ReverseArrayIterator implements Iterator<T> {
int i = n - 1;
public void remove() {
throw new UnsupportedOperationException("");
}
public T next() {
return items[i--];
}
public boolean hasNext() {
return i >= 0;
}
}
public Iterator<T> iterator() {
return new ReverseArrayIterator();
}
public static void main(String[] args) {
}
}