// intLinkedList.cc   P. Conrad  for CISC181 04/06/2007
// read numbers from a file into a linked list

// then search linked list for numbers

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cassert>

#include "intLinkedList.h"


void printListOnOneLine(Node_S *head, std::ostream &out)
{
  // traverse the list
  for (Node_S *q = head; q!=NULL; q=q->next)
    {
      out << q->data << " ";
    }
}

void  addNodeAtEndOfList(Node_S * &head, 
			 Node_S * &tail,
			 int x)
{
   // create a node 
  Node_S *p = new Node_S; 
  p->data = x;            
  p->next = NULL;         

  // add node into list
  
  if (tail==NULL)  
    { 
      assert(head==NULL); // Make sure head is also null
      head = tail = p;    // List was empty.  Now its a singleton
    }
  else
    {
      assert(tail->next == NULL); // Double check that tail points to null
      tail -> next = p;  // Make last element on list point to new one
      tail = p;          // Make new one the last element
    }
}


bool isInList(Node_S *head, int x)
{
  //if x is in list, return true, else return false

  if (head == NULL)
    return false;
  else if (head->data == x)
    return true;
  else
    return isInList(head->next, x);

  return false;
}

void addIntsFromFileToEndOfLinkedList(Node_S *&head, Node_S *&tail, 
				      std::ifstream &infile)
{
  int thisNum;
  
  infile >> thisNum;
  while (!infile.eof())
    {
      addNodeAtEndOfList(head, tail, thisNum); // function call
      infile >> thisNum;  // try to read next number
    }
}


