-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticStack.java
More file actions
59 lines (49 loc) · 1.13 KB
/
StaticStack.java
File metadata and controls
59 lines (49 loc) · 1.13 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
package stack;
public class StaticStack<E> implements Stack<E> {
// Índice do elemento no topo da pilha
protected int top;
// Array que armazena os objetos
protected E elements[];
// @SuppressWarnings("unchecked")
public StaticStack(int maxSize) {
elements = (E[]) new Object[maxSize];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == elements.length - 1;
}
public int numElements() {
return top + 1;
}
public void push(E element) throws OverflowException {
if (isFull())
throw new OverflowException();
elements[++top] = element;
}
public E pop() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
E element = elements[top];
elements[top--] = null;
return element;
}
public E top() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return elements[top];
}
public String toString() {
if (isEmpty())
return "[Empty]";
else {
String s = "[";
for (int i = numElements() - 1; i >= 0; i--) {
s += elements[i] + ",";
}
return s.substring(0, s.length() - 1) + "]";
}
}
}