online: 1; azi: 382; total: 50837 Manual clasa a xi a - Implementarea structurilor de date - Lista liniara

Probleme Rezolvate



Manual clasa a Xi a

Implementarea structurilor de date

Lista liniara

Să se afişeze în ordine inversă numerele dintr-o listă liniară simplu înlănţuită . (Indicație. Se încarcă numerele din listă într-o stivă, în ordinea de parcurgere a listei, şi apoi se extrag şi se afişează numerele din stivă.)
# include < iostream >
# include < fstream >
using namespace std ;
struct Node {
int data;
Node * next ;
};
void push ( Node ** head_ref , int new_data ) {
Node * new_node = new Node ;
new_node ->data = new_data ;
new_node -> next = (* head_ref );
(* head_ref ) = new_node ;
}
void print_list ( Node * node ) {
while ( node != NULL ) {
cout << node ->data << " " ;
node = node -> next ;
}
cout << endl ;
}
void reverse_print_list ( Node * node ) {
if ( node == NULL ) {
return ;
}
reverse_print_list ( node -> next );
cout << node ->data << " " ;
}
int main () {
Node * head = NULL ;
int num;
// Citim lista dintr-un fisier text
ifstream in ( "input.txt" ) ;
while (in >> num) {
push (& head , num);
}
in. close ();
// Afisam lista in ordinea initiala
cout << "Lista initiala : " ;
print_list ( head );
// Afisam lista in ordine inversa
cout << "Lista inversa: " ;
reverse_print_list ( head );
cout << endl ;
return 0 ;
}
# include < iostream >
# include < fstream >
# include < stack >
using namespace std ;
struct Node {
int data;
Node * next ;
};
void push ( Node ** head_ref , int new_data ) {
Node * new_node = new Node ;
new_node ->data = new_data ;
new_node -> next = (* head_ref );
(* head_ref ) = new_node ;
}
void print_list ( Node * node ) {
while ( node != NULL ) {
cout << node ->data << " " ;
node = node -> next ;
}
cout << endl ;
}
void reverse_print_list ( Node * node ) {
stack < int > s;
// Incarcam numerele din lista intr-o stiva
while ( node != NULL ) {
s.push ( node ->data);
node = node -> next ;
}
// Afisam numerele din stiva in ordine inversa
while (! s.empty ()) {
cout << s.top () << " " ;
s.pop ();
}
cout << endl ;
}
int main () {
Node * head = NULL ;
int num;
// Citim lista dintr-un fisier text
ifstream in ( "input.txt" ) ;
while (in >> num) {
push (& head , num);
}
in.close ();
// Afisam lista in ordinea initiala
cout << "Lista initiala : " ;
print_list ( head );
// Afisam lista in ordine inversa
cout << "Lista inversa: " ;
reverse_print_list ( head );
return 0 ;
}