/*****************************************
** This program demonstrates a recursive
** approach to producing a copy of a list,
** i.e. a new list whose nodes have all
** the same values in the same order.
** Doing this iteratively is more difficult!
*****************************************/
#include <iostream>
using namespace std;
/*****************************************
** Struct def's and function prototypes
*****************************************/
struct Node
{
double data;
Node *next;
};
void add2front(double val, Node* &L);
void printlist(Node* L);
Node* copy(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
Node *Lp = copy(L);
// Print both to show they're the same!
printlist(L);
cout << endl;
printlist(Lp);
cout << endl;
return 0;
}
/*****************************************
** Function definitions
*****************************************/
Node* copy(Node* L)
{
// BASE CASE
if (L == 0)
return 0;
// RECURSIVE CASE
Node *C = copy(L->next);
add2front(L->data,C);
return C;
}
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);
}
}