#include <iostream.h>
#include <stddef.h>
#include "bool.H"

struct Node {		// Structure use for building linked structures
    int value;
    Node* next;
};

// Takes a pointer to the first node and traverses the list, printing
// out the value in each node.

void Print(/*in*/ Node* head)
{
    Node* tmp = head;

    while (tmp != NULL)
    {
	tmp = tmp->next;
	cerr << tmp->value << " ";
    } 
    cerr << endl;
}

// Returns true if val is found in the list.  It steps through the list
// comparing the value in each node to val, stopping if val is found.
// If head is NULL at the end, we didn't find val in the list.  If we
// stopped early, it's because we found val so we return TRUE.  Note that
// it's safe to change the head pointer here since it was passed by
// VALUE.  Any modifications we make are undone when we leave the function.

Boolean Member(/*in*/ int val, /*in*/ Node * head)
{
    while (head->value != val)	// Test checks value in current node
    {
	head = head->next;	// Advance if we didn't find it
    }	
    return (head != NULL);	// If head was NULL, return FALSE
}


// Constructs a linked list containing n nodes.  The node values
// are consecutive integers with the first node having a value of 1.
// The list is actually built backwards since it's easier to deal
// with the pointers that way.

Node* Build(/*in*/ int n)
{
    Node* tmp;		// Used to hold pointer to newly-constructed nodes
    Node* head = NULL;	// Pointer to head of list of nodes
    int i;

	for (i=n; i>0; i--)
	{
	    tmp = new Node;	// Make a new node
	    if (tmp == NULL)
	    {
		cerr << "Ran out of memory!" << endl;
		exit(1);
	    }
	    tmp -> value = i;	// Put the proper value in it
	    tmp -> next = head;	// Make it point to the list built so far
	    head = tmp;		// Our new node is now the head of the list
	}
	return head;
}

void TestMember(Node* list)
{
	if (Member(3, list)) 
	    cerr << "3 is member" << endl;
	else
	    cerr << "3 is not a member" << endl;
	if (Member(10, list)) 
	    cerr << "10 is member" << endl;
	else
	    cerr << "10 is not a member" << endl;
}


int main()
{
    Node* list;

	list = Build(5);		// Build list (1 2 3 4 5)
	cerr << "List elements are: ";	
	Print(list);			// Print contents of list
	cerr << "About to test the function Member..." << endl;
	TestMember(list);		// Now see if Member works
}

