-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
77 lines (62 loc) · 1.97 KB
/
Stack.java
File metadata and controls
77 lines (62 loc) · 1.97 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
import java.util.Iterator;
public class Stack<Item> implements Iterable<Item>{
private int count;
private Item[] a;
private String stringOutput = "";
public Stack() { //Constructor with initial stack size of 2
a = (Item[]) new Object[2];
}
public void push(Item item) { //Push an item onto the stack
if (count == a.length)
upsize();
a[count++] = item;
}
public void upsize() { //Double the size of the stack if the stack is full
Item[] temp = (Item[]) new Object[2*a.length];
for (int i=0; i < count; i++) {
temp[i] = a[i];
}
a = temp;
}
public Item pop() { //Pop an item of the stack
Item item = a[--count];
a[count] = null;
if (!isEmpty() && count == (a.length/4))
downsize();
return item;
}
public void downsize() { //Halve the size of the stack if stack is 1/4 full
Item[] temp = (Item[]) new Object[a.length/2];
for (int i=0; i < count; i++) {
temp[i] = a[i];
}
a = temp;
}
public boolean isEmpty() { //Check if stack is empty
return count == 0;
}
public int size() { //Returns size of the stack
return count;
}
public String toString() { //toString implementation
while (!isEmpty()) {
String test = ""+pop();
if (!test.equals("null"))
stringOutput += ""+pop()+"\n";
}
return("Stack contains " +count+" items:\n " + stringOutput);
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i = count;
public boolean hasNext() {
return i > 0;
}
public Item next() {
return a[--i];
}
public void remvove() {}
}
}