class Pila
{
private int[] elementos = null;
private int tope;
public Pila()
{
elementos = new int[5];
tope = -1;
}
public Pila(int n)
{
if (n < 1)
n = 5;
elementos = new int[n];
tope = -1;
}
//Indexador
// es el que nos permiten el acceso a un miembro de la clase mientras mantiene el control asociado al
// acceso mediante métodos.
public int this[int index]
{
get { return elementos[index]; }
}
public int Maximo
{
get { return elementos.Length; }
}
public int Tope
{
get { return tope; }
}
public bool estaVacia()
{
return tope == -1;
}
public bool estaLlena()
{
return tope == elementos.Length - 1;
}
public bool Poner(int x)
{
if (estaLlena())
return false;
tope++;
elementos[tope] = x;
return true;
}
public bool Quitar(ref int x)
{
if (estaVacia())
return false;
x = elementos[tope];
tope--;
return true;
}
public override string ToString()
{
if (estaVacia())
return "{}";
string p = "{";
for (int i = 0; i <= tope; i++)
{
p = p + elementos[i].ToString();
if (i == tope)//es el último elemento de la pila
p = p + "}";
else
p = p + ",";
}
return p;
}
}
}
//--------------------------------------------------------------
public partial class Form1 : Form
{
Pila enteros = new Pila(10);
public Form1()
{
InitializeComponent();
}
public void Mostrar()
{
dgv.Rows.Clear();
if (enteros.estaVacia())
return;
int r = 0;
for (int i = enteros.Tope; i >=0; i--)
{
dgv.Rows.Add();
dgv[0, r].Value = i;
dgv[1, r].Value = enteros[i];
r++;
}
}
private void botPoner_Click(object sender, EventArgs e)
{
int dato;
try
{
dato = Convert.ToInt32(textDato.Text);
}
catch
{
MessageBox.Show("Teclee un dato entero por favor...");
return;
}
if (enteros.estaLlena())
{
MessageBox.Show("Pila llena compare.. no hay lugar para más elementos");
return;
}
if (enteros.Poner(dato))
Mostrar();
else
MessageBox.Show("No se pudo poner el dato");
}
private void botAleatorio_Click(object sender, EventArgs e)
{
Random r = new Random();
textDato.Text = r.Next(0, 101).ToString();
botPoner_Click(sender, e);
}
private void botQuitar_Click(object sender, EventArgs e)
{
if(enteros.estaVacia())
{
MessageBox.Show("La pila esta vacía, no se pueden quitar elementos...");
return;
}
int dato = 0;
if (enteros.Quitar(ref dato))
{
textDato.Text = dato.ToString();
Mostrar();
}
else
MessageBox.Show("No se pudo quitar un dato");
}
}
}
No hay comentarios:
Publicar un comentario