I'm doing a program with a menu to load, delete and display a linked list through the list and node class. The problem is that sometimes all the values are loaded normally, and sometimes the program crashes after loading one or two values. If I try to create a list and the charge is outside the do-while menu, the program only loads 17 elements. If I try to load one more, the program closes.
#include <iostream>
#include <string.h>
#include <cstring>
#include "Nodo.h"
#include "Stack.h"
#include "Lista.h"
using namespace std;
void menu(){
cout<<"1: Ingresar cliente "<<endl;
cout<<"2: Eliminar cliente "<<endl;
cout<<"3: Visualizar clientes "<<endl;
cout<<"4: Salir "<<endl;
}
int main(){
Lista <string> l;
string name;
int op,pos;
do{
menu();
cin >> op;
switch(op){
case 1:
cout<<"Ingrese Nombre\n";
cin>>name;
l.insertValue(name);
break;
case 2:
cout<<"Ingrese cliente a eliminar\n";
cin>>pos;
l.deleteAt(pos);
break;
case 3:
l.printList();
}
system("pause");
system("cls");
}while(op!=4);
Lista <string> l1;
return 0;
}
List.h
#include "Nodo.h"
#include <iostream>
#ifndef _LISTA_H
#define _LISTA_H
using namespace std;
template <class T> class Lista{
protected:
T dato;
Nodo<T>* lista;
public:
Lista(){
lista=0;
}
void deleteAt(int p){
Nodo<T>* temp = lista;
if(p==1){
lista=lista->obtenerEnlace();
free(temp);
}
else{
for(int i =0;i<p-2;i++) temp=temp->obtenerEnlace();
Nodo<T>* temp2 =temp->obtenerEnlace();
temp->ponerEnlace(temp2->obtenerEnlace());
free(temp2);
}
}
void insertValue(T d){
Nodo<T> * nuevo =(Nodo<T>*)malloc(sizeof(Nodo<T>));
nuevo->ponerDato(d);
nuevo->ponerEnlace(lista);
lista=nuevo;
}
void printList(){
Nodo<T> * temp =lista;
while(temp!=0){
cout<<temp->obtenerDato()<<endl;
temp=temp->obtenerEnlace();
}
}
};
#endif
Node.h
#ifndef _NODO_H
#define _NODO_H
template <class T> class Nodo{
protected:
T dato;
Nodo<T> * enlace;
public:
Nodo(T d){
enlace=0;
dato=d;
}
Nodo(T d,Nodo * n){
enlace=n;
dato=d;
}
Nodo<T>* obtenerEnlace() const{
return enlace;
}
void ponerEnlace(Nodo * n){
enlace=n;
}
void ponerDato(T d){
dato=d;
}
T obtenerDato() const{
return dato;
}
};
#endif