-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
65 lines (55 loc) · 1.28 KB
/
LinkedStack.java
File metadata and controls
65 lines (55 loc) · 1.28 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
package stack;
public class LinkedStack<E> implements Stack<E> {
protected Node<E> top;
protected int numElements;
public LinkedStack() {
top = null;
numElements = 0;
}
public boolean isEmpty() {
return numElements == 0;
}
public boolean isFull() {
// uma pilha com alocação dinâmica nunca estará cheia!
return false;
}
public int numElements() {
return numElements;
}
public void push(E element) {
// cria um novo nodo e retorna o novo "top"
Node<E> newNode = new Node<E>(element);
newNode.setNext(top);
top = newNode;
numElements++;
}
public E pop() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
// guarda uma referência ao elemento atualmente no topo
E element = top.getElement();
// o novo topo passa a ser o elemento abaixo do atual
top = top.getNext();
// ajusta o total de elementos
numElements--;
return element;
}
public E top() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return top.getElement();
}
public String toString() {
if (isEmpty())
return "[Empty]";
else {
String s = "[";
Node<E> cur = top;
while (cur != null) {
s += cur.getElement() + ",";
cur = cur.getNext();
}
return s.substring(0, s.length() - 1) + "]";
}
}
}