/***************************************** ** This program demonstrates an iterative ** approach to producing a reverse copy of ** a list, i.e. a new list whose nodes have ** all the same values in the reverse order. ** Doing this recursively is more difficult! *****************************************/ #include <iostream> using namespace std; /***************************************** ** Class def's and function prototypes *****************************************/ class Node { public: double data; Node *next; }; void add2front(double val, Node* &L); void printlist(Node* L); Node* reverse(Node* L); /***************************************** ** MAIN *****************************************/ int main() { // Get original list of values from user Node *L = 0; double x; while(cin >> x) add2front(x,L); // Make copy in reverse Node *Lp = reverse(L); // Print both to show they're reverses! printlist(L); cout << endl; printlist(Lp); cout << endl; return 0; } /***************************************** ** Function definitions *****************************************/ Node* reverse(Node* L) { Node* R = 0; for(Node *p = L; p != 0; p = p->next) add2front(p->data,R); return R; } void add2front(double val, Node* &L) { Node *T = new Node; T->data = val; T->next = L; L = T; } void printlist(Node* L) { if (L != 0) { cout << L->data << ' '; printlist(L->next); } }