-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.java
More file actions
112 lines (94 loc) · 2.39 KB
/
Stack.java
File metadata and controls
112 lines (94 loc) · 2.39 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Stack implemented using dynamically sized array.
* @author James Pope
* @param <Type>
*/
public class Stack <Type> implements Iterable<Type>
{
private static final int DEFAULT_CAPACITY = 8;
private Type[] items;
private int size;
public Stack()
{
this.items = (Type[])new Object[DEFAULT_CAPACITY];
this.size = 0;
}
public void push(Type item)
{
// If not eough room , expand
if( this.size == this.items.length )
{
grow();
}
this.items[size] = item;
this.size++;
}
public Type pop()
{
if( this.isEmpty() )
{
throw new IllegalArgumentException("No item to pop");
}
this.size--;
Type item = this.items[size];
this.items[size] = null; // prevent loitering
return item;
}
public Type peek()
{
return this.items[size-1];
}
public int size()
{
return this.size;
}
public boolean isEmpty()
{
return this.size == 0;
}
private void grow()
{
Type[] newItems = (Type[])new Object[this.items.length*2];
System.arraycopy(this.items, 0, newItems, 0, this.items.length);
this.items = newItems;
}
@Override
public String toString()
{
StringBuilder buf = new StringBuilder();
buf.append("[");
for (int i = 0; i < this.size; i++)
{
Type item = items[i];
if( i != 0 ) buf.append(", ");
buf.append( item.toString() );
}
buf.append("]");
return buf.toString();
}
public Iterator<Type> iterator()
{
return new Iterator()
{
private int currentIndex = size - 1;
public boolean hasNext()
{
return currentIndex >= 0;
}
public Object next()
{
if( currentIndex < 0 )
{
throw new NoSuchElementException("No more elements");
}
return items[currentIndex--];
}
public void remove()
{
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
}