#include "node.h"
#include "linkedlist.h"
#include <cstdlib>
#include <cassert>

LinkedList::LinkedList(){
  head = NULL;
}

LinkedList::~LinkedList(){
  clear();
}

LinkedList::LinkedList(const LinkedList& rhs){
  *this = rhs; // why reinvent the wheel... just use the = operator :) 
}

const LinkedList& LinkedList::operator=(const LinkedList& rhs){
  if( this != &rhs ){
    clear();  // release the memory of the current linked list
    
    if( rhs.head == NULL ){
      head = NULL;
    }else{
      head = new Node(rhs.head->value());

      Node* finger = rhs.head->next();
      Node* current = head;

      while( finger != NULL ){
	current->setNext(new Node(finger->value()));
	current = current->next();
	finger = finger->next();
      }
    }
  }

  return *this;
}

void LinkedList::addFirst(int value){
  head = new Node(value, head);
}

int LinkedList::removeFirst(){
  assert(head != NULL);

  int returnMe = head->value();
  Node* oldHead = head;
  head = head->next();
  delete oldHead;
  return returnMe;
}

int LinkedList::getFirst() const{
  return head->value();
}
 
bool LinkedList::contains(int value) const{
  Node* finger = head;

  while( finger != NULL && finger->value() != value ){
    finger = finger->next();
  }

  return finger != NULL;
}

void LinkedList::set(int index, int value){
  Node* finger = head;

  for( int i = 0; i < index && head != NULL; i++ ){
    finger = finger->next();
  }

  if( finger != NULL ){
    finger->setValue(value);
  }
}

void LinkedList::clear(){
  while( !isEmpty() ){
    removeFirst();
  }
}

bool LinkedList::isEmpty(){
  return head == NULL;
}
