// LinkedList.cpp

// Implements some of the functionality of the singly linked list
// (check the header file for the inlined definitions).

// Author: Dr. Jeffrey Blessing

#include "LinkedList.h"

// destructor implementation:

LinkedList::~LinkedList()
{
	// loop thru list destroying nodes
	start();
	while (ptr != NULL)
	{
		Node* tmp = ptr->next;

		delete ptr;
		ptr = tmp;
	}
}

// copy constructor implementation:

LinkedList::LinkedList(const LinkedList& src)
{
	// create hdr cell
	head = tail = ptr = new Node();
	Node* p = src.head;
	Node* t = head;

	// copy the data elements
	while (p->next != NULL)
	{	t->next = new Node();
		p = p->next;			// skip the header cell
		t = t->next;
		t->data = p->data;
		if (p == src.ptr) ptr = t;
	}

	// take care of last node
	tail = t;
}

// assignment operator implementation:

LinkedList& LinkedList::operator=(const LinkedList& src)
{
	// check first for self assignment
	if (this != &src)
	{
		// Destroy the dest list, then copy the src list into
		// this object's current location using the "placement
		// new" operator (Lippman's C++ Primer 3rd Ed. Ex. 13.7)
		this->~LinkedList();
		new (this) LinkedList(src);
	}
	return *this;
}

// globally overloaded << operator

ostream& operator<<(ostream& os, const LinkedList& src)
{
	Node* p = src.head;

	do
	{	p = p->next;			// skip the header cell
		os << p->data << ", ";
	} while (p->next != NULL);

	return os;
}