lunes, 20 de septiembre de 2010

IMPLEMENTACION DE PILA

#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
//Definicion de la Estructura
struct nodoPila
{
    int dato;
    nodoPila *sig;};
    //Menu principal
int menu()
{
    int opc;
    clrscr();
    cout<<"       MENU PRINCIPAL";
    cout<<"\n1. Inicializar Pila";
    cout<<"\n2. Apilar (push)";
    cout<<"\n3. Recorrer Pila";
    cout<<"\n4. Desapilar (pop)";
    cout<<"\n5. Salir";
    cout<<"\nOpcion: ";
    cin>>opc;
    return opc;
}
//Definicion de funciones
 void inicializar(struct nodoPila **);
 void desapilar(struct nodoPila **);
 void recorrer(struct nodoPila **);
 void apilar(struct nodoPila **, int x);
//Funcion recorrer
 void recorrer(struct nodoPila **tope)
 {clrscr();
    struct nodoPila *aux;
    if(*tope==NULL)
        cout<<"\nPila Vacia. ";
    else
    {
        aux=*tope;
        while(aux!=NULL)
        {
            cout<<"Elemento: "<<aux->dato<<"\n";
            aux=aux->sig;
        }
    }
    getch();
}
//Funcion inicializar
 void inicializar(struct nodoPila **tope)
 { clrscr();
    *tope=NULL;
    cout<<"\nPila Inicializada.";
    getch();
 }
//Funcion apilar
 void apilar(struct nodoPila **tope, int dat)
 { clrscr();
    struct nodoPila *aux;
    aux=new nodoPila;
    if(aux==NULL)
     {
        cout<<"\nMemoria Insuficiente. ";
        getch();
     }
    aux->dato=dat;
    aux->sig=*tope;
    *tope=aux;
 }
//Funcion desapilar
 void desapilar(struct nodoPila **tope)
 { clrscr();
    struct nodoPila *aux;
    if(*tope==NULL)
        cout<<"Pila Vacia";
    else
     {
        aux=*tope;
        cout<<"Elemento eliminado: "<<(*tope)->dato;
        *tope=(*tope)->sig;
        delete aux;
     }
    getch();
 }
//Cuerpo principal
 int main()
 {
   struct nodoPila *tope;
    int dat,opc;
    do
     {
        opc=menu();
        switch(opc)
        {
            case 1:{inicializar(&tope);break;}
            case 2:{
                    cout<<"\nEntre el dato: ";
                    cin>>dat;
                    apilar(&tope,dat);
                    break;
                }
            case 3:{recorrer(&tope);break;}
            case 4:{desapilar(&tope);break;}
        }
    }while(opc!=5);
    return 0;
}