Pilha Fila Estatica

download Pilha Fila Estatica

of 36

Transcript of Pilha Fila Estatica

  • 7/24/2019 Pilha Fila Estatica

    1/36

    Tipos Especiais de Listas

    Pilha

    Fila

  • 7/24/2019 Pilha Fila Estatica

    2/36

    2

    Tipos especiais de listas

    O armazenamento seqencial (esttico) til quando

    as estruturas sofrem poucas remoesouinseres ou ainda quando inseres e remoesno acarretam grande movimentao de ns No bem o caso da implementao de lista que permite

    remover e inserir um elemento em qualquer posio da

    lista... Por isso, o armazenamento seqencial mais usado para

    implementar os tipos especiais de listas:

    Filas (Queue em ingls),

    Pilhas (Stack em ingls) e

    Deques (Deque em ingls) So mais ferramentas do programador do que estruturas de

    armazenamento.

  • 7/24/2019 Pilha Fila Estatica

    3/36

    Pilha

    (Stack)

  • 7/24/2019 Pilha Fila Estatica

    4/36

    4

    Pilhas (stack)

    Os elementos so inseridos e removidos sempre em umaextremidade (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.

    Pilha Vazia: topo=-1

    5

    4

    32

    1

    0 17

    push (17)Insero de 17 no topo da pilha

    topo

  • 7/24/2019 Pilha Fila Estatica

    5/36

    Pilhas (Stack)

    Operaes sobre Pilhas:

    Verificar se a pilha est vazia

    Verificar se a pilha est cheia

    Inserir um elemento no topo da pilhaRemover um elemento do topo da pilhaInspecionar o elemento do topo da pilha

  • 7/24/2019 Pilha Fila Estatica

    6/36

    6

    Pilhas

    5

    4

    32

    1

    0 17

    push (17)Insero de 17 no topo da pilha

    top

  • 7/24/2019 Pilha Fila Estatica

    7/36

    7

    5

    43

    2

    1

    0 17

    push(5)

    Insero de 5 no topo da pilha

    5

    5

    4

    32

    1

    0 17

    pop()Remoo (sempre no topo da pilha)

    top

    top

  • 7/24/2019 Pilha Fila Estatica

    8/36

    8

    5

    43

    2

    1

    0 17

    push(123)

    Insero de 123 no topo da pilha

    123

    5

    4

    3

    2

    1

    0 17

    push(25)Insero de 25 no topo da pilha

    123

    25

    top

    top

  • 7/24/2019 Pilha Fila Estatica

    9/36

    9

    5

    43

    2

    1

    0 17

    push(12)Insero de 12 no topo da pilha

    123

    5

    4

    3

    2

    1

    0 17

    pop()Remoo (sempre no topo da pilha)

    123

    25

    25

    12 top

    top

  • 7/24/2019 Pilha Fila Estatica

    10/36

    10

    Estouro de pilhas: Estouro negativo (underflow): pilha vazia sofre

    operao de extrao

    Estouro positivo (overflow): quando a insero de umelemento excede a capacidade total da pilha.

  • 7/24/2019 Pilha Fila Estatica

    11/36

    11

    Interface Stack

    publicinterfaceStack {

    /** Return the number of elements in the stack. */publicintnumElements();

    /** Return whether the stack is empty. */publicbooleanisEmpty();

    /** Return whether the stack is full. */publicbooleanisFull();

    /** Inspect the element at the top of the stack.*/publicE top() throwsEmptyStackException;

    /**Insert an element at the top of the stack.*/

    publicvoidpush (E element);

    /** Remove the top element from the stack.*/publicE pop() throwsEmptyStackException;

    }

  • 7/24/2019 Pilha Fila Estatica

    12/36

    12

    Classe StaticStack

    publicclassStaticStack implementsStack {

    // ndice do elemento no topo da pilhaprotectedinttop;

    // Array que armazena as referncias para os elementosprotectedE elements[];

    // Constroi uma pilha com um tamanho mximopublicStaticStack(int maxSize) {

    elements= (E[])newObject[maxSize];top= -1;

    }

  • 7/24/2019 Pilha Fila Estatica

    13/36

    Classe StaticStack (cont.)

    /**Returns the number of elements in the stack. */publicintnumElements() {return(top+ 1);

    }

    /**Testes whether the stack is empty. */publicbooleanisEmpty() {returntop== -1;

    }

    /**Testes whether the stack is full. */public boolean isFull() {returntop== elements.length 1;

    }

  • 7/24/2019 Pilha Fila Estatica

    14/36

    14

    /**Inserts an element at the top of the stack. */publicvoidpush(E element) throwsOverflowException {

    if(isFull())thrownewOverflowException();

    elements[++top] = element;}

    /** Inspects the element at the top of the stack. */publicE top() throws UnderflowException {if(isEmpty())thrownewUnderflowException();

    returnelements[top];

    }

    Classe StaticStack (cont.)

  • 7/24/2019 Pilha Fila Estatica

    15/36

    15

    Classe StaticStack (cont.)

    /**Removes the top element from the stack. */

    publicE pop() throwsUnderflowException {if(isEmpty())thrownewUnderflowException ();

    E element = elements[top];elements [top--] = null; // para a coleta de lixo.returnelement;

    }}

  • 7/24/2019 Pilha Fila Estatica

    16/36

    Classe StaticStack (cont.)

    /*** Returns a string representation of the stack as a list of

    elements.*/publicString toString() {

    if(isEmpty())

    return [Empty] ;

    else{

    String s = "[";for(inti = numElements() - 1; i >= 0; i--) {

    s += "\n"+ elements[i];}s+= "\n"+ "]"+ "\n";

    returns;

    }}

    16

  • 7/24/2019 Pilha Fila Estatica

    17/36

    Testando a Pilha

    17

    publicclassStaticStackTest {publicstaticvoidmain(String[] args) {

    StaticStack s = newStaticStack(10);

    try{ s.push(1);s.push(2);s.push(3);s.push(4);s.push(5);

    } catch(UnderflowExceptione) {

    System.out.println(e);}

    try{while(!s.isEmpty()) {

    System.out.println(s.pop());}

    }catch(UnderflowExceptione){System.out.println(e);

    }}

    }

  • 7/24/2019 Pilha Fila Estatica

    18/36

    Exerccio

    18

    Implemente um mtodo que inverta o contedo de uma pilha passadacomo parmetro. Para isso considere a seguinte assinatura:

    public void invertePilha(Stack s)

  • 7/24/2019 Pilha Fila Estatica

    19/36

    Fila(Queue)

  • 7/24/2019 Pilha Fila Estatica

    20/36

    20

    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)

    FIFO(first-int, first-out)

    primeiro a entrar, primeiro a sair

    Fila vazia:

    Quando last==first-1;

    Underflow: fila vazia sofreoperao de extrao

    Overflow: quando a insero deum elemento excede acapacidade total da fila.

    1 2 3 4 5 6 7

  • 7/24/2019 Pilha Fila Estatica

    21/36

    Operaes sobre Filas (Queue)

    Verificar se a fila est vazia

    Inserir um elemento no final da fila

    Remover e retornar o elemento do inicioda fila

    Consultar o elemento do inicio da fila

    Obter o tamanho da fila

  • 7/24/2019 Pilha Fila Estatica

    22/36

    22

    Operaes da Fila

    0 1 2 3 4 5

    fila vaziafirst==-1

    0 1 2 3 4 5

    90 12 117

    fila cheiafirst==0 &&last==v.length-1

    first last

    8 6

    0 1 2 3 4 5

    7

    first

    last

    0 1 2 3 4 5

    907 8 6

    first last

    0 1 2 3 4 5

    90 12 117

    firstlast

    0 1 2 3 4 5

    4 12 113

    fila cheiafirst==last+1

    firstlast

    5 6

  • 7/24/2019 Pilha Fila Estatica

    23/36

    Fila com implementao circular

    0 1 2 3 4 5

    incio da filafim da fila

    90 12 117

  • 7/24/2019 Pilha Fila Estatica

    24/36

    24

    Interface Queue

    publicinterfaceQueue {/** Returns the number of elements in the queue.*/

    publicintnumElements();/** Returns whether the queue is empty. */publicbooleanisEmpty();/** Returns whether the queue is full. */public boolean isFull();/** Inspects the element at the front of the queue.*/publicE front() throwsUnderflowException;/** Inspects the element at the back of the queue.*/public E back() throws UnderflowException;/** Inserts an element at the rear of the queue. */publicvoidenqueue (E element) throws OverflowException;

    /** Removes the element at the front of the queue.*/publicE dequeue() throwsUnderflowException;

    }

  • 7/24/2019 Pilha Fila Estatica

    25/36

    25

    Classe StaticQueue

    publicclassStaticQueue implementsQueue{

    //Index to the first elementprotectedintfirst;

    //Index to the last element

    protectedintlast;

    // Generic array used to store the elementsprotectedE elements[];

    publicStaticQueue(intmaxSize) {elements= (E[]) newObject[maxSize];

    first= last= -1;}

  • 7/24/2019 Pilha Fila Estatica

    26/36

    26

    Classe StaticQueue (cont.)

    /** Testes whether the queue is empty. */publicbooleanisEmpty() {

    return first == -1;}

    publicbooleanisFull() {returnfirst== ((last+ 1) % elements.length);

    }

    /** Returns the number of elements in the queue. */publicintnumElements() {

    if (isEmpty())return 0;

    else {int n = elements.length;

    return ((n + last first) % n) + 1;

    }}

  • 7/24/2019 Pilha Fila Estatica

    27/36

    27

    Classe StaticQueue (cont.)

    /** Inspects the element at the front of the queue.*/publicE front() throwsUnderflowException {if(isEmpty())

    thrownewUnderflowException ();returnelements[first];

    }

    /** Inspects the element at the back of the queue.*/publicE back() throwsUnderflowException {

    if(isEmpty())thrownewUnderflowException ();

    returnelements[last];

    }

  • 7/24/2019 Pilha Fila Estatica

    28/36

    28

    Classe StaticQueue (cont.)

    /** Inserts an element at the rear of the queue. */publicvoidenqueue(E element) throwsOverflowException {

    if(isFull())thrownewOverflowException();

    else{

    if(last== -1)first= last= 0;

    elselast= (last+ 1) % elements.length;

    elements[last] = element;}

    }

  • 7/24/2019 Pilha Fila Estatica

    29/36

    29

    Classe StaticQueue (cont.)

    /** Removes and return the element at the front of the queue.*/publicE dequeue() throwsUnderflowException {

    if(isEmpty())thrownewUnderflowException();

    E element = elements[first];elements[first] = null; // p/ coleta de lixo

    if(first== last)first= last= -1;else

    first= (first+ 1) % elements.length;

    returnelement;}

    Testando a Fila

  • 7/24/2019 Pilha Fila Estatica

    30/36

    30

    Testando a Fila

    publicclassStaticQueueTest {publicstaticvoidmain(String[] args) {

    StaticQueue q = newStaticQueue(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);}

    }}

    i

  • 7/24/2019 Pilha Fila Estatica

    31/36

    Exerccio

    Implemente mtodos para exibir o contedo da filacircular de 2 maneiras:1.

    No mtodo main, faa o cdigo necessrio para queenquanto a fila no for vazia, esvazie a fila, exibindo oselementos retirados.

    2. Crie um mtodo toString() na classe StaticQueue queretorne uma String com o contedo da fila na ordem emque foram inseridos

    E i

  • 7/24/2019 Pilha Fila Estatica

    32/36

    Exerccios

    Dada 2 pilhas ordenadas deelementos a partir do topo,escreva o cdigo necessrio paraque o contedo das pilhas sejaminserido em uma terceira pilha deforma tambm ordenada. O

    contedo das pilhas iniciais podeser removido.

    32

    E i

  • 7/24/2019 Pilha Fila Estatica

    33/36

    Exerccios

    33

    E i

  • 7/24/2019 Pilha Fila Estatica

    34/36

    Exerccios

    Uma palavra um palndromose tem a mesmaseqncia de letras, quer seja lida da esquerda paraa direita ou da direita para a esquerda (exemplo:raiar). Escrever pelo menos 2 algoritmos paraverificar se uma palavra um palndromo, usandopilha(s) e/ou fila(s). Compare esses algoritmos do

    ponto de vista de eficincia e consumo de memria.

    34

    E i

  • 7/24/2019 Pilha Fila Estatica

    35/36

    Exerccios

    Escreva um procedimento para inverter a ordem doselementos de uma fila, usando uma pilha comoestrutura auxiliar.

    35

    E i

  • 7/24/2019 Pilha Fila Estatica

    36/36

    Exerccios

    36

    A estrutura de dados conhecida como Deque (do ingls

    double queue) permite a insero e remoo de elementosapenas nas extremidades.

    Com isso em mente implemente a classe StaticDeque. Estaclasse deve utilizar um vetor como estrutura dearmazenamento e deve permitir inseres e remoes

    apenas nas extremidades (inicio e fim).