// file:          OwnerOfList.hpp
// description:   Container of a simply linked list with random initialization.
//                Usable as Mixin.
//                Sak A16(7)(b), Sak A1.
//                Caution: No destructor provided for OwnerOfList and Node!
//                Dynamically created Node-objects on the heap are never deleted!
// author:        Karlheinz Hug
// creation date: 2012-06-20
// last update:   2012-07-02

#ifndef OWNER_OF_LIST_HPP_
#define OWNER_OF_LIST_HPP_

#include <cassert>

#include "ToolsetRandomC.hpp"

	template <typename T>
	class OwnerOfList
		// Instantiation condition: T is a comparable type.
	{
		protected:
			struct Node
			{
				T      item;
				Node * next;
			};

			Node * first,
			     * last,
			     * current;

			virtual void init_list (unsigned int size, T min_item, T max_item, bool has_sentinel);

			virtual ~OwnerOfList();
	}; // OwnerOfList

	template <typename T>
	void OwnerOfList<T>::init_list (unsigned int size, T min_item, T max_item, bool has_sentinel)
	{
		assert(min_item <= max_item); // precondition
		if (has_sentinel)
		{
			last       = new Node();
			last->next = 0;
			first      = last;
		}
		for (unsigned int index = 0; index < size; ++index)
		{
			current       = new Node();
			current->item = ToolsetRandom<T>::uniform (min_item, max_item);
			current->next = first;
			first         = current;
		}
	}

	template <typename T>
	OwnerOfList<T>::~OwnerOfList ()
	{
		typename OwnerOfList<T>::Node * pos = this->first;
		while (pos)
		{
			pos = pos->next;
			delete this->first;
			this->first = pos;
		}
	}

#endif // OWNER_OF_LIST_HPP_
