Lista enlazada simple: Insertar por posicion

#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 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<<" 4. 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:
                cout << "\n\n MOSTRANDO LISTA\n\n";
                mostrarLista(lista);
            break;
        }

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

    }while(op!=5);


   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