A class based implementation of linked lists

A class based impelementation of linked lists. Learnt really basic C style lists at school, so I thought I’d go the whole hog and implement a class based interface. Taught myself templates while doing this! Now, I have to resist the urge to template nearly every damn function. Use this implementation by declaring an object of the list class. Add nodes using the push(data) and push_back(data) functions, and remove nodes using pop() and pop_back() functions.

// list.h
#include <iostream>

using namespace std;

template <class data_type>
class list
{
struct node
{
data_type data;
node *next;
node *prev;
};

node *top;
node *back;

int nNodes;
bool indexed;
public:
list();
list(data_type);
void push_back(data_type);
void push(data_type);
void pop();
void pop_back();
friend ostream& operator << (ostream &out, list &l)
{
node *iter= l.top;
while(iter != nullptr)
{
out << iter->data << " ";
iter = iter->next;
}

return out;
}
data_type operator[](int);
};

template <class data_type> list<data_type>::list()
{
top = nullptr;
back = nullptr;
nNodes = 0;
}

template <class data_type> void list<data_type>::push_back(data_type data) //push a new element onto the list (from behind)
{
node *new_node = new node;
new_node->next = nullptr;
new_node->prev = back;
new_node->data = data;

back->next = new_node;
back = back->next;
nNodes++;
}

template <class data_type> void list<data_type>::push(data_type data) //push an new element onto the list (from the top)
{
node *new_node = new node;
new_node->next = top;
new_node->prev = nullptr;
new_node->data = data;

top = new_node;

if(top->next == nullptr)
back = top;

nNodes++;
}

template <class data_type> void list<data_type>::pop() //pop off top element of the list
{
node* delete_node = top;
top = top->next;

delete delete_node;
nNodes--;
}

template <class data_type> void list<data_type>::pop_back() //pop off last element of the list
{
node* delete_node = back;
back = back->prev;
back->next = nullptr;

delete delete_node;
}

template <class data_type> data_type list<data_type>::operator[](int index)//displaye element[x] of the list
{
node *iter = top;
for(int i = 0; i < index && iter->next != nullptr; i++)
{
iter = iter->next;
}

return iter->data;
}

Advertisements
Previous Post
Next Post
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: