>Write a ClassTemplate for a linked list.
I think it means write a linked list class that uses templates for the type, not whatever you were trying to do with a vector.
Infusing myself with the power of concentrated ugly, I wrote this for you. Maybe you can glean something out of it for your own project. Yes, I know it's probably way more than you're expected to do:
#include <iostream>
using namespace std;
template <typename T>
class linked_list {
class Node {
friend class Iterator;
friend class linked_list;
public:
Node ( T init, Node *link ): data ( init ), next ( link ) {}
private:
T data;
Node *next;
};
class Iterator {
friend class linked_list;
public:
Iterator(): node ( 0 ) {}
Iterator ( Node *link ): node ( link ) {}
Iterator ( const Iterator& it )
: node ( new Node ( it.node->data, it.node->next ) ) {}
Iterator *operator++() { node = node->next; return this; }
T& operator*() { return node->data; }
friend bool operator!= ( const Iterator& a, const Iterator& b )
{
return a.node != b.node;
}
private:
Node *node;
};
public:
typedef Iterator iterator;
linked_list(): n ( 0 ) {}
template <typename Iter>
linked_list ( Iter first, Iter last ): n ( 0 )
{
while ( first != last ) {
push_back ( *first++ );
++n;
}
}
void push_front ( const T& item )
{
list.node = new Node ( item, list.node );
++n;
}
void push_back ( const T& item )
{
if ( list.node == 0 )
list.node = new Node ( item, 0 );
else {
Node *it = list.node;
while ( it->next != 0 )
it = it->next;
it->next = new Node ( item, it->next );
}
}
iterator begin() { return list; }
iterator end() { return Iterator(); }
int size() { return n; }
private:
iterator list;
int n;
};
template <typename T, int N>
char (&array(T(&)[N]))[N];
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,0};
double b[] = {1.2,2.3,3.4,4.5,5.6,6.7};
linked_list<int> list1 ( a, a + sizeof array ( a ) );
linked_list<double> list2 ( b, b + sizeof array ( b ) );
linked_list<int>::iterator it1 = list1.begin();
while ( it1 != list1.end() ) {
cout<< *it1 <<"->";
++it1;
}
cout<<endl;
linked_list<double>::iterator it2 = list2.begin();
while ( it2 != list2.end() ) {
cout<< *it2 <<"->";
++it2;
}
cout<<endl;
} It's ugly and far from good. I put less than 30 minutes work into it, sue me.
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401