Home > Development > C++ Linked List

C++ Linked List


This took me a while to get working as I am no expert yet at C++ programming. But now that I have sucessfully put it together I feel my C++ skills are progressing.
A few quick notes this is not a generic list. It only works for integers and at some later point I will change it to support generics.

#include <iostream>

using namespace std;

class Node{
private:
    int value;
    Node* next;
public:
    friend class List;
    Node();
    void setValue(int value);
    int getValue() const;
};

Node::Node(){
    value = 0;
    next = 0;
}

void Node::setValue(int value){
    this->value = value;
}

int Node::getValue() const{
    return this->value;
}

class List{
private:
    int totalitems;
    Node* head;
    Node* tail;
public:
    List();
    ~List();
    void addValue(int value);
    void addStart(int value);
    void print();
    int count();
};

List::List(){
    totalitems = 0;
    head = 0;
    tail = 0;
}

List::~List(){

    Node* current = head;
    while(current != 0){
        Node* temp = current->next;
        delete current;
        current = temp;
    }

}

void List::addValue(int value){
    Node* node = new Node();
    node->setValue(value);
    ++totalitems;


    if(head == 0){
        head = node;
        tail = node;
        return;
    }

    tail->next = node;
    tail = tail->next;

}

void List::addStart(int value){
    Node* node = new Node();
    node->setValue(value);
    ++totalitems;

    if(head == 0){
        head = node;
        tail = node;
        return;
    }

    Node* temp = head;
    head = node;
    head->next = temp;

}

void List::print(){

    Node* start = head;

    while(start != 0){
        cout << start->getValue() << endl;
        start = start->next;
    }

}

int List::count(){
    return totalitems;
}

int main(){

    List list = List();
    list.addValue(1);
    list.addValue(2);
    list.addValue(3);
    list.addValue(4);
    list.addValue(5);
    list.addValue(6);
    list.addValue(7);
    list.addStart(10);

    cout << list.count() << endl << endl;

    list.print();
    return 0;
}

cout Blair šŸ™‚

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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: