online: 4; azi: 184; total: 52190 Manual clasa a xi a - Implementarea structurilor de date - Lista liniara

Probleme Rezolvate



Manual clasa a Xi a

Implementarea structurilor de date

Lista liniara

Se inversează ordinea numerelor dintr-o coadă cu ajutorul unei stive.
# include < iostream >
# include < fstream >
# include < string >
# include < sstream >
struct Nod {
int val;
Nod* urm;
};
struct Coada {
Nod* inceput ;
Nod* sfarsit ;
};
struct Stiva {
Nod* varf ;
};
void init_coada (Coada& coada) {
coada.inceput = nullptr ;
coada.sfarsit = nullptr ;
}
void init_stiva (Stiva& stiva) {
stiva.varf = nullptr ;
}
bool coada_goala ( const Coada& coada) {
return coada.inceput == nullptr ;
}
bool stiva_goala ( const Stiva& stiva) {
return stiva.varf == nullptr ;
}
void push_coada (Coada& coada, int val) {
Nod* nod_nou = new Nod{val, nullptr };
if ( coada_goala (coada)) {
coada.inceput = nod_nou ;
} else {
coada.sfarsit ->urm = nod_nou ;
}
coada.sfarsit = nod_nou ;
}
void push_stiva (Stiva& stiva, int val) {
Nod* nod_nou = new Nod{val, stiva.varf };
stiva.varf = nod_nou ;
}
void pop_coada (Coada& coada) {
if ( coada_goala (coada)) {
throw std :: runtime_error ( "Coada este goala." );
}
Nod* nod_vechi = coada.inceput ;
coada.inceput = nod_vechi ->urm;
if ( coada.inceput == nullptr ) {
coada.sfarsit = nullptr ;
}
delete nod_vechi ;
}
void pop_stiva (Stiva& stiva) {
if ( stiva_goala (stiva)) {
throw std :: runtime_error ( "Stiva este goala." );
}
Nod* nod_vechi = stiva.varf ;
stiva.varf = nod_vechi ->urm;
delete nod_vechi ;
}
int front_coada ( const Coada& coada) {
if ( coada_goala (coada)) {
throw std :: runtime_error ( "Coada este goala." );
}
return coada.inceput ->val;
}
int top_stiva ( const Stiva& stiva) {
if ( stiva_goala (stiva)) {
throw std :: runtime_error ( "Stiva este goala." );
}
return stiva.varf ->val;
}
void inverseaza_coada (Coada& coada) {
Stiva stiva ;
init_stiva (stiva);
while (! coada_goala (coada)) {
push_stiva (stiva, front_coada (coada));
pop_coada (coada);
}
while (! stiva_goala (stiva)) {
push_coada (coada, top_stiva (stiva));
pop_stiva (stiva);
}
}
int main () {
Coada coada ;
init_coada (coada);
// Citirea numerelor pentru coada din fisierul "numere.txt"
std :: ifstream fisier ( "numere.txt" ) ;
std :: string linie;
std :: getline ( fisier , linie);
fisier. close ();
std :: istringstream iss (linie) ;
int numar ;
while ( iss >> numar ) {
push_coada (coada, numar );
}
// Inversarea ordinii numerelor din coada
inverseaza_coada (coada);
// Afisarea elementelor din coada inversata
while (! coada_goala (coada)) {
std :: cout << front_coada (coada) << " " ;
pop_coada (coada);
}
return 0 ;
}