#define NULL 0

#include "List.h"

#include <iostream>

 

using namespace std;

 

// Constructor

// Initialize the head pointer to NULL

List::List()

{

  head = NULL;

}

 

List::~List()

{

  Node* temp = head;

  Node* previous = NULL;

 

  while( temp != NULL )

    {

      previous = temp;

      temp = temp->getnext();

      delete previous;

    }

}

 

// Put a data item into the linked list (at the head)

void List::insert( int item )

{

  Node* temp = head;

  head = new Node( item );

  head->setnext( temp );

}

 

// Return the nth element in the linked list

int List::get( int n )

{

  Node* temp = head;

 

  for ( int i = 0; i < n; i++ )

    {

      temp = temp->getnext();

    }

 

  return temp->getdata();

}

 

 

// Delete the nth element from the linked list

void List::erase( int n )

{

  Node* temp = head;

  Node* to_erase = NULL;

 

  // Delete the head

  if ( n == 0 )

    {

      to_erase = head;

      head = head->getnext();

    }

  else // Delete something down the list

    {

      for ( int i = 0; i < n-1; i++ )

      {

        cout << "Looked at node:" << temp->getdata();

        temp = temp->getnext();

      }

     

      to_erase = temp->getnext();

      cout << "Going to erase: " << to_erase->getdata();

     

      temp->setnext( to_erase->getnext() );

      cout << "Set temp->next = " << to_erase->getnext() << endl;

    }

 

  delete to_erase;

}