// L-21 MCS 360 Mon 11 Oct 2010 : recursive_on_STL_list.cpp

/* The program below illustrates how to recursive define a list
   of n random integer numbers and to print that list recursively.
   Similar to writing is the searching for an element in a list. */

#include <list>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

// set v to 1 to make routines verbose 
#define v 0

list<int> generate ( int n );
// returns a list of n random integers

void write ( list<int> L);
// writes the list

bool belongs ( list<int> L, int e );
// returns true if e belongs to L, false otherwise

int main()
{
   cout << "Give number of elements : ";
   int n; cin >> n;

   cout << "generating " << n 
        << " random numbers ...\n";
   list<int> L = generate(n);
   cout << "the list :";
   write(L); cout << endl;

   cout << "give a number : ";
   int i; cin >> i;

   cout << i;
   if(belongs(L,i))
      cout << " is in the list\n";
   else
      cout << " is not in the list\n";

   return 0;
}

list<int> generate ( int n )
{
   if(v) cout << "generate with n = " << n << " ...\n";
   if(n <= 0)
   {
      list<int> L;
      if(v) cout << "returning empty list" << endl;
      return L;
   }
   else
   {
      int r = rand() % 1000;
      list<int> L = generate(n-1);
      if(v) cout << "pushing " << r << " to front ..." << endl;
      L.push_front(r);
      return L;
   }
}

void write ( list<int> L )
{
   if(v) cout << "in write with list of size " 
              << L.size() << endl;
   if(!L.empty())
   {
      list<int> K = L;
      cout << " " << K.front();
      K.pop_front();
      write(K);
   }
}

bool belongs ( list<int> L, int e )
{
   if(L.empty())
      return false;
   else if(L.front() == e)
      return true;
   else
   {
      list<int> K = L;
      K.pop_front();
      return belongs(K,e);
   }
}

