Ir para conteúdo
Fórum Script Brasil
  • 0

Implementação de filas com prioridades


addNextLufe

Pergunta

Para a execução de um trabalho da faculdade eu preciso implementar prioridade em uma fila.

O professor não está disponível para retirada de dúvidas há 4 dias e o prazo de entrega do trabalho é hoje às 23:00, alguma dica de como proceder?

Me foram disponibilizados 4 arquivos, sendo 1 de teste:

package br.paduan;

/**
 * ARQUIVO 1 - App.java
 */
public final class App {
    private App() {
    }

    /**
     * Says hello to the world.
     * @param args The arguments of the program.
     */
    public static void main(String[] args) {
        Lista lista = new Lista();

        lista.addEnd("Huguinho");
        lista.addEnd("Zezinho");
        lista.addEnd("Luizinho");
        lista.addStart("Patinhas");

        System.out.println(lista.show());

        No temp = lista.removeName("Huguinho");
        System.out.println("Removeu " + temp.getName());

        System.out.println(lista.show());

    }
}
package br.paduan;

/*
 * ARQUIVO 2 - Lista.java
 */

public class Lista {
    private No first;

    public Lista(){
        first = null;
    }

    public boolean isEmpty(){
        return first == null;
    }

    public void addEnd(String name){
        No newNode = new No(name);
        if(isEmpty()){
            first = newNode;
        }else{
            No aux = first;
            while(aux.getNext() != null){
                aux = aux.getNext();
            }
            aux.setNext(newNode);
        }
    }

    public void addStart(String name){
        if(isEmpty()){
            addEnd(name);
        }else{
            No newNode = new No(name);
            newNode.setNext(first);
            first = newNode;
        }
    }

    public No removeStart(){
        if(isEmpty()){
            return null;
        }
        No aux = first;

        first = first.getNext();

        return aux;
    }

    public No removeEnd(){
        if(isEmpty()){
            return null;
        }
        No aux = first;
        No previous = null;

        while(aux.getNext() != null){
            previous = aux;
            aux = aux.getNext();
        }
        
        if(previous == null){
            first = null;
        }else{
            previous.setNext(null);
        }
        return aux;
    }

    public boolean exist(String name){
        if(!isEmpty()){
            No aux = first;
            while(aux != null){
                if(aux.getName().equals(name)){
                    return true;
                }
                aux = aux.getNext();
            }          
        }
        return false;
    }


    public No removeName(String name){
        if(!isEmpty()){
            No aux = first;
            No previous = aux;
            while(aux != null){
                if(aux.getName().equals(name)){
                    if(aux == first){
                        return removeStart();
                    }
                    if(aux.getNext() == null){
                        return removeEnd();
                    }
                    previous.setNext(aux.getNext());
                    return aux;
                }
                previous = aux;
                aux = aux.getNext();
            }          
        }
        return null;        
    }

    public String show(){
        String out = "";

        No aux = first;

        while(aux != null){
            out += aux.getName() + ";" ;
            aux = aux.getNext();
        }

        return out;
    }

}
package br.paduan;

/*
 *  ARQUIVO 3 - No.java
 */

public class No {
    private String name;
    private No next;

    public No(String name){
        this.name = name;
        next = null;
    }

    public String getName(){
        return name;
    }

    public No getNext(){
        return next;
    }

    public void setNext(No next){
        this.next = next;
    }
}
package br.paduan;

/*
 * ARQUIVO 4 - ListaTest.java
 */

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Before;

public class ListaTest {

    private FilaPriority fila;

    private final String name1 = "Nome1";
    private final String name2 = "Nome2";
    private final String name3 = "Nome3";

    private final int priority1 = 1;
    private final int priority2 = 2;
    private final int priority3 = 3;

    @Before
    public void setup() {
        fila = new FilaPriority();
    }

    @Test
    public void testIsEmpty() {
        boolean vazia = fila.isEmpty();

        assertTrue("Uma fila nova deve iniciar vazia.", vazia);
    }

    @Test
    public void testNotEmpty() {

        fila.add(name1, priority1);
        boolean vazia = fila.isEmpty();

        assertFalse("Uma fila com um elemento não deve estar vazia.", vazia);
    }

    @Test
    public void testAddEndOnEmptyList() {

        fila.add(name1, priority1);
        String out = fila.show();

        String expected = name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção deve ser exibido o nome " + name1, expected, out);
    }

    @Test
    public void testAddHighestPriority() {

        fila.add(name1, priority1);
        fila.add(name2, priority2);
        String out = fila.show();

        String expected = name2 + "(" + priority2 + ")" + ";" + name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testLowestPriority() {

        fila.add(name2, priority2);
        fila.add(name1, priority1);
        String out = fila.show();

        String expected = name2 + "(" + priority2 + ")" + ";" + name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testAddMiddlePriority() {

        fila.add(name1, priority1);
        fila.add(name3, priority3);
        fila.add(name2, priority2);
        String out = fila.show();

        String expected = name3 + "(" + priority3 + ")" + ";" + name2 + "(" + priority2 + ")" + ";" + name1 + "("
                + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testAddRepeatedPriorityOnStart() {

        fila.add(name1, priority1);
        fila.add(name3, priority3);
        fila.add(name2, priority2);
        fila.add(name3, priority3);
        String out = fila.show();

        String expected = name3 + "(" + priority3 + ")" + ";" + name3 + "(" + priority3 + ")" + ";" + name2 + "("
                + priority2 + ")" + ";" + name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testAddRepeatedPriorityOnEnd() {

        fila.add(name1, priority1);
        fila.add(name3, priority3);
        fila.add(name2, priority2);
        fila.add(name1, priority1);
        String out = fila.show();

        String expected = name3 + "(" + priority3 + ")" + ";" + name2 + "(" + priority2 + ")" + ";" + name1 + "("
                + priority1 + ")" + ";" + name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testAddRepeatedPriorityOnMiddle() {

        fila.add(name1, priority1);
        fila.add(name2, priority2);
        fila.add(name3, priority3);
        fila.add(name2, priority2);
        String out = fila.show();

        String expected = name3 + "(" + priority3 + ")" + ";" + name2 + "(" + priority2 + ")" + ";" + name2 + "("
                + priority2 + ")" + ";" + name1 + "(" + priority1 + ")" + ";";

        assertEquals("Após inserção de dois nomes amobos deve ser exibidos respeitando a ordem", expected, out);
    }

    @Test
    public void testRemoveOnEmptyList() {

        Node removido = fila.remove();

        assertEquals("Remoção de uma fila vazia deve retornar null", null, removido);
    }

    @Test
    public void testRemoveLastItem() {

        fila.add(name1, priority1);

        String nome = fila.remove().getName();
        boolean vazia = fila.isEmpty();

        assertEquals("Deve ser removido o nome que estava no início da fila", name1, nome);
        assertTrue("A Fila ficou fazia", vazia);
    }

    @Test
    public void testRemoveStart() {

        fila.add(name1, priority1);
        fila.add(name2, priority2);

        String nome = fila.remove().getName();

        assertEquals("Deve ser removido o nome que estava no início da fila", name2, nome);
    }

    @Test
    public void testPeekOnEmptyQueue(){
        Node primeiro = fila.peek();

        assertEquals("Se a fila está fazia o primeiro elemento é null", null, primeiro);
    }

    @Test
    public void testPeek(){
        fila.add(name1, priority1);

        Node primeiro = fila.peek();

        assertEquals("Validando o primeiro elmento da fila", name1, primeiro.getName());
    }

}

 

Link para o comentário
Compartilhar em outros sites

0 respostass a esta questão

Posts Recomendados

Até agora não há respostas para essa pergunta

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,8k
×
×
  • Criar Novo...