-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResizingArrayStack.java
49 lines (43 loc) · 1.21 KB
/
ResizingArrayStack.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
import java.util.Iterator;
public class ResizingArrayStack<Item> implements Iterable<Item>
{
private Item[] a = (Item[]) new Object[1];
private int N = 0;
public boolean isEmpty() { return N == 0; }
public int size() { return N; }
// Make the stack resizable through array copying.
private void resize(int cap)
{ // Copy the contents of a to a new array, and make it new instance var.
Item[] temp = (Item[]) new Object[cap];
for (int i = 0; i < N; i++)
{
temp[i] = a[i];
}
a = temp;
}
public void push(Item item)
{
if (N == a.length) resize(a.length*2);
a[N] = item;
N++;
}
public Item pop()
{
N--;
Item item = a[N];
a[N] = null; // Avoid loitering.
if (N > 0 && N == a.length/4) resize(a.length/2);
return item; // Need to insert null?
}
// Make the stack iterable.
// Iterable parent class expects an iterator() fn.
public Iterator<Item> iterator()
{ return new ReverseArrayIterator(); }
private class ReverseArrayIterator implements Iterator<Item>
{
private int i = N;
public boolean hasNext() { return i > 0; }
public Item next() { return a[i--]; }
public void remove() { }
}
}