-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathStack.java
More file actions
63 lines (53 loc) · 1.24 KB
/
Copy pathStack.java
File metadata and controls
63 lines (53 loc) · 1.24 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
import java.lang.Iterable;
import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>
{
// get an iterator
public Iterator<Item> iterator() { return new ReverseArrayIterator(); }
private class ReverseArrayIterator implements Iterator<Item>
{
private int current = N-1;
public boolean hasNext()
{
return current >= 0;
}
public void remove()
{
// not implemented
}
public Item next()
{
Item item = s[current--];
return item;
}
}
private Item[] s;
private int N;
public Stack()
{
this.s = (Item[])new Object[1];
this.N = 0;
}
private void resize(int capacity)
{
// O(N)
Item[] copy = (Item[])new Object[capacity];
for (int i = 0; i < N; i++)
copy[i] = s[i];
s = copy;
}
public void push(Item item)
{
// O(1)
if (N == s.length) resize(N*2);
s[N++] = item;
}
public Item pop()
{
// O(1)
Item item = s[--N];
s[N] = null;
if (N == s.length/4) resize(s.length/2);
return item;
}
}