-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticStack.java
More file actions
67 lines (58 loc) · 1.59 KB
/
StaticStack.java
File metadata and controls
67 lines (58 loc) · 1.59 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
package Etapa3;
/**
* Implementação de uma pilha estática genérica.
* @param <E> Tipo de elemento armazenado na pilha.
*/
@SuppressWarnings("unchecked")
public class StaticStack<E> implements Stack<E> {
private int top;
private Object[] elements;
/**
* Construtor da pilha estática.
* @param maxSize Tamanho máximo da pilha.
*/
public StaticStack(int maxSize) {
if (maxSize <= 0) throw new IllegalArgumentException("Tamanho inválido");
this.elements = new Object[maxSize];
this.top = -1;
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public boolean isFull() {
return top == elements.length - 1;
}
@Override
public int numElements() {
return top + 1;
}
@Override
public void push(E element) {
if (isFull()) throw new OverflowException();
elements[++top] = element;
}
@Override
public E pop() {
if (isEmpty()) throw new UnderflowException();
E e = (E) elements[top];
elements[top--] = null;
return e;
}
@Override
public E top() {
if (isEmpty()) throw new UnderflowException();
return (E) elements[top];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("StaticStack[");
for (int i = 0; i <= top; i++) {
sb.append(elements[i]);
if (i < top) sb.append(", ");
}
sb.append("]");
return sb.toString();
}
}