Lista enlazada simple: Eliminar Final

#include <iostream>
using namespace std;

struct nodo{
       int nro;      
       struct nodo *sgte;
};

typedef struct nodo *Tlista;
void insertarInicio(Tlista &lista, int valor)
{
    Tlista q;
    q = new(struct nodo);
    q->nro = valor;
    q->sgte = lista;
    lista  = q;
}

void insertarFinal(Tlista &lista, int valor)
{
    Tlista t, q = new(struct nodo);

    q->nro  = valor;
    q->sgte = NULL;

    if(lista==NULL)
    {
        lista = q;
    }
    else
    {
        t = lista;
        while(t->sgte!=NULL)
        {
            t = t->sgte;
        }
        t->sgte = q;
    }
}

void insertarPosicion(Tlista lista,int valor,int p){
 int n=1;
 Tlista q,t=lista,ant;
 q=new(struct nodo);
 q->nro=valor;
 q->sgte=NULL;
 while(n!=p&&t->sgte!=NULL){
  ant=t;
  n++;
  t=t->sgte;
 }
 q->sgte=t;
 ant->sgte=q;
}
void eliminarUltimoElemento(Tlista & lista){
 Tlista aux,ant;
 int n=1;
 aux=lista;
 if(lista!=NULL){
  while(aux->sgte!=NULL){
   ant=aux;
   n++;
   aux=aux->sgte;
  }
  ant->sgte=NULL;
  delete(aux);
  }
  else{
   cout<<"lista vacia"<<endl;
  }
}

void mostrarLista(Tlista lista)
{
     int i = 0;
     while(lista != NULL)
     {
          cout <<" [" <<i+1 <<"] " << lista->nro << endl;
          lista = lista->sgte;
          i++;
     }
}
int main()
{
    Tlista lista = NULL;
    int op;    
    int dato; 
    int pos;  

    do
    {
        cout<<"\n\t\tLISTA ENLAZADA SIMPLE\n\n";
     cout<<" 1. INSERTAR AL INICIO               "<<endl;
     cout<<" 2. INSERTAR AL FINAL                "<<endl;
     cout<<" 3. INSERTAR EN UNA POSICION         "<<endl;
     cout<<" 5. ELIMINAR ULTIMO ELEMENTO         "<<endl;
     cout<<" 8. MOSTRAR LISTA                    "<<endl;
     cout<<"\n INGRESE OPCION: ";
  cin>> op;

        switch(op)
        {
            case 1:
                cout<< "\n NUMERO A INSERTAR: "; cin>> dato;
                insertarInicio(lista, dato);
             break;
           
            case 2:
                cout<< "\n NUMERO A INSERTAR: "; cin>> dato;
                insertarFinal(lista, dato );
             break;
           
            case 3:
                cout<< "\n NUMERO A INSERTAR: ";cin>>dato;
                cout<< " Posicion : ";       cin>> pos;
                insertarPosicion(lista, dato, pos);
             break;
           
                   
            case 4:
                eliminarUltimoElemento(lista);
             break;
           
            case 5:
                cout << "\n\n MOSTRANDO LISTA\n\n";
                mostrarLista(lista);
             break;
        }

        cout<<endl<<endl;
        system("pause");  system("cls");

    }while(op!=6);


   system("pause");
   return 0;
}

Comentarios

Entradas más populares de este blog

Invertir número

Numero capicua

Hallar el dígito mayor de un numero