Implementing a queue using array Learn programming Java

Lesson:

Dynamic Memory Management


Exercise:

Implementing a queue using array 43


Objetive:

Implementing a queue


Code:

import java.util.*;

public class Cola
{
	private int[] pila;
	private int posicion;
	private int tamanyo;

	public Cola(int tamanyo)
	{
		posicion = -1;
		this.tamanyo = tamanyo;

		// Iniciamos el array
		pila = new int[this.tamanyo];
	}

	public final void Encolar(int valor)
	{
		// Aumentamos posición
		posicion++;

		// Guardamos el valor
		pila[posicion] = valor;
	}

	public final int Desencolar()
	{
		int aux = pila[0];

		for (int i = 0; i < posicion; i++)
		{
			pila[i] = pila[i + 1];
		}

		pila[posicion] = aux;

		posicion--;

		// Retornamos el ultimo valor
		return pila[posicion + 1];
	}
}

public class TestCola
{
	public static void main(String[] args)
	{
		boolean depurando = false;

		Cola cola = new Cola(2);

		cola.Encolar(1);
		cola.Encolar(2);

		System.out.println(cola.Desencolar());
		System.out.println(cola.Desencolar());

		if (depurando)
		{
			new Scanner(System.in).nextLine();
		}
	}
}