-
Notifications
You must be signed in to change notification settings - Fork 857
Expand file tree
/
Copy pathGenericStack.java
More file actions
60 lines (53 loc) · 1.36 KB
/
GenericStack.java
File metadata and controls
60 lines (53 loc) · 1.36 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
public class GenericStack<E> {
private E[] list = (E[])new Object[10];
private int size = 0;
/** Return the number of elements in the stack */
public int getSize() {
return size;
}
/** Return the top element from the stack */
public E peek() {
return list[size - 1];
}
/** Push a new element to the top of the stack */
public void push(E o) {
if (size >= list.length) {
doubleList();
}
list[size++] = o;
}
/** Return and remove the top element from the stack */
public E pop() {
if (--size < 0)
size = 0;
E o = list[size];
E[] new_list = (E[]) new Object[list.length];
System.arraycopy(list, 0, new_list, 0, size);
list = new_list;
return o;
}
/** Test whether the stack is empty */
public boolean isEmpty() {
return size == 0;
}
/** Create a new array that is double the current array size
* and copy the elements from the current array to the new array */
private void doubleList() {
E[] tempList = (E[])new Object[list.length * 2];
System.arraycopy(list, 0, tempList, 0, list.length);
list = tempList;
}
@Override // Override the toString array in the Object class
public String toString() {
String s = "Stack: [";
if (isEmpty())
return s + "]";
for (int i = 0; i < size; i++) {
if (i == size-1)
s += list[i].toString() + "]";
else
s += list[i].toString() + ", ";
}
return s;
}
}