domingo, 25 de agosto de 2013

Colas

Interfaz a Utilizar:

package Colas;

/**
 * @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
 */
public interface IQueue<E>{
    public void add(E target);
    public boolean isEmpty();
    public void print();
    public E remove();
}
La clase Queue

package Colas;

/**
 * @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
 */
public class Queue<E> implements IQueue<E>{
    
    E[] data;
    
    public Queue(){
        data=(E[])new Object[0];
    }
    
    /**
     * Agrega elemento al final de la cola
     */
    public void add(E target) {
        E[] temp=(E[])new Object[data.length+1];
        if(!isEmpty())
            for(int i=0; i<data.length; i++)
                temp[i]=data[i];
        temp[data.length]=target;
        data=temp;
    }

    public boolean isEmpty() {
        return data.length==0;
    }

    public void print() {
        System.out.print("[");
        for(int i=0; i<data.length; i++){
            if(i==data.length-1)
                System.out.print(data[i]);
            else
                System.out.print(data[i]+",");
        }
        System.out.println("]");
    }
    
    /**
     * Remueve el primer elemento de la estructura y lo retorna
     */
    public E remove() {
        if(!isEmpty()){
            E firstElement=data[0];
            E[]temp=(E[])new Object[data.length-1];
            for(int i=0; i<data.length-1; i++)
                temp[i]=data[i+1];
            data=temp;
            return firstElement;
        }
        return null;
    }   
}
La clase principal

package Colas;

/**
 * @author Daniel Cataño Restrepo <dasniel199410@gmail.com>
 */
public class Main {

    public static void main(String[] args) {
        Queue q=new Queue();
        q.add(1);
        q.add(2);
        q.add(3);
        q.add(4);
        q.add(1);
        q.add(2);
        q.add(3);
        q.add(4);
        q.print();
        q.remove();
        q.remove();
        q.print();
    }
}

No hay comentarios:

Publicar un comentario