#include <iostream>
template <typename T> class SinglyLinkedList
{
struct node
{
T val;
node * next;
};
public:
SinglyLinkedList ();
SinglyLinkedList (T *, size_t);
~SinglyLinkedList ();
void push_back (const T &);
void print ();
void remove_val (const T &);
private:
node * _root;
};
int main ()
{
int myArray [] = { 1, 69, -23942, 69, 56, 67 };
SinglyLinkedList<int> myList(myArray, sizeof(myArray)/sizeof(int));
myList.push_back(33);
myList.remove_val(69);
myList.print();
return 0;
}
template <typename T> SinglyLinkedList<T>::SinglyLinkedList ( )
{
_root = NULL;
}
template <typename T> SinglyLinkedList<T>::SinglyLinkedList (T * arr, size_t n)
{
/* Initialize a singly-linked list of objects of type T from an array of objects of type T */
if (n > 0)
{
node * lastNode = new node;
lastNode->val = *arr;
lastNode->next = NULL;
_root = lastNode;
++arr;
for (T * offend(arr+n); arr != offend; ++arr)
{
node * thisNode = new node;
thisNode->val = *arr;
thisNode->next = NULL;
lastNode->next = thisNode;
lastNode = thisNode;
}
}
else
{
_root = NULL;
}
}
template <typename T> SinglyLinkedList<T>::~SinglyLinkedList ( )
{
node * thisNode = _root;
while (thisNode != NULL)
{
node * temp = thisNode;
thisNode = thisNode->next;
delete temp;
}
}
template <typename T> void SinglyLinkedList<T>::push_back ( const T & v )
{
node * newNode = new node;
newNode->val = v;
newNode->next = NULL;
if (_root != NULL)
{
node * thisNode = _root;
while (thisNode->next != NULL) thisNode = thisNode->next;
thisNode->next = newNode;
}
else
{
_root = newNode;
}
}
template <typename T> void SinglyLinkedList<T>::print ( )
{
if (_root == NULL) return;
for (node * thisNode = _root; thisNode != NULL; thisNode = thisNode->next)
{
std::cout << thisNode->val << " --> ";
}
std::cout << "NULL";
}
template <typename T> void SinglyLinkedList<T>::remove_val ( const T & v )
{
if (_root == NULL) return;
node * lastNode = _root;
if (lastNode->val == v && lastNode->next == NULL) delete lastNode;
node * thisNode = lastNode->next;
while (thisNode != NULL)
{
if (thisNode->val == v)
{
node * temp = thisNode;
thisNode = thisNode->next;
lastNode->next = thisNode;
delete temp;
}
else
{
thisNode = thisNode->next;
}
}
}