#include<iostream>
#include<string>
using namespace std;
/*Def di una struttura nodo*/
struct nodo
{
int val;
nodo *next;
};
/*classe Exception personalizzata*/
class MiaEx : public std::exception
{
std::string _msg;
public:
MiaEx(const std::string& msg) : _msg(msg){}
virtual const char* what() const noexcept override
{
return _msg.c_str();
}
};
/*classe vettore dinamico*/
class vect
{
private:
int dim;
nodo *testa;
public:
vect()
{
/*inizializzo gli attributi*/
dim=0;
testa=new nodo;
testa=NULL;
}
/*Aggiunge un nodo in coda*/
void append(int v)
{
nodo *e=new nodo;
e->val=v;
nodo *tmp=testa;
if(!tmp)
{
testa=e;
e->next=NULL;
}
else
{
while(tmp->next)
tmp=tmp->next;
tmp->next=e;
e->next=NULL;
}
/*aggiorno la dimensione*/
dim++;
}
/*ritorna la copia di un valore all'indice index*/
int push(int index)
{
nodo *tmp=testa;
try
{
if(index>=dim) throw MiaEx("Indice fuori dimensione\n");
for(int i=0;i<=index-1;i++)
{
tmp=tmp->next;
}
return tmp->val;
}catch(MiaEx e)
{
cout<<e.what()<<endl;
return (int)NULL;
}
}
/*rimuove un elemento alla posizione index*/
void remove(int index)
{
nodo *tmp=testa;
nodo *prec=testa;
try
{
if(!testa) throw MiaEx("Lista Vouta\n");
if(index>=dim) throw MiaEx("Indice fuori dimensione\n");
if(index==0)
{
testa=testa->next;
}
else
{
for(int i=0;i<index;i++)
{
/*devo memorizzare il riferiemnto al precedente*/
prec=tmp;
tmp=tmp->next;
}
prec->next=tmp->next;
delete tmp;
}
dim--;
}catch(MiaEx e)
{
cout<<e.what()<<endl;
}
}
/*Ritorna la dimensione del vettore*/
int getDim()
{
return dim;
}
/*ovveride dell'operatore <<*/
friend ostream& operator<<(ostream& out, const vect* v) {
nodo *tmp=v->testa;
try
{
if(!tmp) throw MiaEx("Lista vuota\n");
while(tmp)
{
out << tmp->val << " ";
tmp=tmp->next;
}
return out;
}catch (MiaEx e)
{
out<<e.what()<<endl;
return out;
}
}
};
Post Views: 817