Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Pilha
Fila
Pilha
(Stack)
Pilhas (stack)
Os elementos so inseridos e removidos sempre em uma
extremidade (a final) chamada de topo da pilha.
Contm um ponteiro (varivel) que marca o topo da pilha.
Implementa norma: LIFO (last-in, first-out)
ltimo a entrar, primeiro a sair.
push (17)
Insero de 17 no topo da pilha
4
3
2
1
0
17
topo
4
Pilhas (Stack)
Pilhas
push (17)
Insero de 17 no topo da pilha
4
3
2
1
0
17
top
6
push(5)
Insero de 5 no topo da pilha
4
3
2
5
0 17
1
top
pop()
Remoo (sempre no topo da pilha)
4
3
2
1
0
17
top
7
push(123)
Insero de 123 no topo da pilha
4
3
2
1 123
0
17
push(25)
Insero de 25 no topo da pilha
4
3
2
top
25
top
1 123
0
17
8
push(12)
Insero de 12 no topo da pilha
5
4
3
12
25
top
1 123
0
17
pop()
Remoo (sempre no topo da pilha)
4
3
2
25
top
1 123
0
17
9
Estouro de pilhas:
Estouro negativo (underflow): pilha vazia sofre
operao de extrao
Estouro positivo (overflow): quando a insero de um
elemento excede a capacidade total da pilha.
10
Interface Stack<E>
public interface Stack<E> {
/** Return the number of elements in the stack. */
public int numElements();
/** Return whether the stack is empty. */
public boolean isEmpty();
/** Return whether the stack is full. */
public boolean isFull();
/** Inspect the element at the top of the stack.*/
public E top() throws EmptyStackException;
/**Insert an element at the top of the stack.*/
public void push (E element);
/** Remove the top element from the stack.*/
public E pop() throws EmptyStackException;
}
11
Classe StaticStack
public class StaticStack<E> implements Stack<E> {
// ndice do elemento no topo da pilha
protected int top;
// Array que armazena as referncias para os elementos
protected E elements[];
// Constroi uma pilha com um tamanho mximo
public StaticStack(int maxSize) {
elements = (E[])new Object[maxSize];
top = -1;
}
12
/**Returns the number of elements in the stack. */
public int numElements() {
return (top + 1);
}
/**Testes whether the stack is empty. */
public boolean isEmpty() {
return top == -1;
}
/**Testes whether the stack is full. */
public boolean isFull() {
return top == elements.length 1;
}
/** Inserts an element at the top of the stack. */
public void push(E element) throws OverflowException {
if (isFull())
throw new OverflowException();
elements[++top] = element;
}
/** Inspects the element at the top of the stack. */
public E top() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
return elements[top];
}
14
/** Removes the top element from the stack. */
public E pop() throws UnderflowException {
if (isEmpty())
throw new UnderflowException ();
E element = elements[top];
elements [top--] = null; // para a coleta de lixo.
return element;
}
}
15
16
Testando a Pilha
public class StaticStackTest {
public static void main(String[] args) {
StaticStack<Integer> s = new StaticStack<Integer>(10);
try{
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
} catch(UnderflowException e) {
System.out.println(e);
}
try{
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
catch(UnderflowException e){
System.out.println(e);
}
}
}
17
Exerccio
Implemente um mtodo que inverta o contedo de uma pilha passada
como parmetro. Para isso considere a seguinte assinatura:
public void invertePilha(Stack<E> s)
18
Fila
(Queue)
Filas (Queue)
Elementos so inseridos no fim da fila e retirados do incio da fila.
Geralmente, a implementao, contm 2 ponteiros (variveis):
Um ponteiro para o incio da fila (first)
Um ponteiro para o fim da fila (last)
Fila vazia:
Quando last==first-1;
20
Operaes da Fila
fila vazia first==-1
0
3 4
last
0
3 4
fila cheia
first==0 &&
last==v.length-1
2
3 4
7 90 8 6 12 11
first
last
3 4
last
first
first
7 90 8 6
fila cheia
first==last+1
0
7 90
last
3 4
12 11
first
3 4
3 4
6 12 11
last first
22
7 90
fim da fila
3 4
12 11
incio da fila
Interface Queue
public interface Queue<E> {
/** Returns the number of elements in the queue.*/
public int numElements();
/** Returns whether the queue is empty. */
public boolean isEmpty();
/** Returns whether the queue is full. */
public boolean isFull();
/** Inspects the element at the front of the queue.*/
public E front() throws UnderflowException;
/** Inspects the element at the back of the queue.*/
public E back() throws UnderflowException;
/** Inserts an element at the rear of the queue. */
public void enqueue (E element) throws OverflowException;
/** Removes the element at the front of the queue.*/
public E dequeue() throws UnderflowException;
}
24
Classe StaticQueue
25
/** Testes whether the queue is empty. */
public boolean isEmpty() {
return first == -1;
}
public boolean isFull() {
return first == ((last + 1) % elements.length);
}
/** Returns the number of elements in the queue. */
public int numElements() {
if (isEmpty())
return 0;
else {
int n = elements.length;
return ((n + last first) % n) + 1;
}
}
26
27
28
/** Removes and return the element at the front of the queue.*/
public E dequeue() throws UnderflowException {
if (isEmpty())
throw new UnderflowException();
E element = elements[first];
elements[first] = null; // p/ coleta de lixo
if (first == last)
first = last = -1;
else
first = (first + 1) % elements.length;
return element;
}
29
Testando a Fila
public class StaticQueueTest {
public static void main(String[] args) {
StaticQueue<Integer> q = new StaticQueue<Integer>(5);
try{
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
q.enqueue(4);
q.dequeue();
q.dequeue();
q.enqueue(5);
q.enqueue(6);
q.enqueue(7);
} catch(OverflowException e) {
System.out.println(e);
}
catch(UnderflowException e) {
System.out.println(e);
}
}
}
30
Exerccio
Implemente mtodos para exibir o contedo da fila
circular de 2 maneiras:
1. No mtodo main, faa o cdigo necessrio para que
enquanto a fila no for vazia, esvazie a fila, exibindo os
elementos retirados.
2. Crie um mtodo toString() na classe StaticQueue que
retorne uma String com o contedo da fila na ordem em
que foram inseridos
Exerccios
Dada 2 pilhas ordenadas de
elementos a partir do topo,
escreva o cdigo necessrio para
que o contedo das pilhas sejam
inserido em uma terceira pilha de
forma tambm ordenada. O
contedo das pilhas iniciais pode
ser removido.
32
Exerccios
33
Exerccios
Uma palavra um palndromo se tem a mesma
seqncia de letras, quer seja lida da esquerda para
a direita ou da direita para a esquerda (exemplo:
raiar). Escrever pelo menos 2 algoritmos para
verificar se uma palavra um palndromo, usando
pilha(s) e/ou fila(s). Compare esses algoritmos do
ponto de vista de eficincia e consumo de memria.
34
Exerccios
Escreva um procedimento para inverter a ordem dos
elementos de uma fila, usando uma pilha como
estrutura auxiliar.
35
Exerccios
A estrutura de dados conhecida como Deque (do ingls
double queue) permite a insero e remoo de elementos
apenas nas extremidades.
Com isso em mente implemente a classe StaticDeque. Esta
classe deve utilizar um vetor como estrutura de
armazenamento e deve permitir inseres e remoes
apenas nas extremidades (inicio e fim).
36