Saturday, October 19, 2013

Doubly Linked List

So after spending so much more time than I ever want to spend on linked lists, I've written what I believe to be working code for it.

//Node.h
struct Node
{
    unsigned int val;
    Node* next;
    Node* prev;
};

//linkedlist.h

struct Node;

class LinkedList
{
    Node* front;
    Node* back;
    unsigned int size;
public:
    LinkedList();
    ~LinkedList();
    void pushBack(int val);
    void popBack();
    void pushFront(int val);
    void popFront();
    int getFront();
    int getBack();
    bool isEmpty();
};

linkedlist.cpp
#include"linkedList.h"
#include"Node.h"

LinkedList::LinkedList()
    : front(nullptr), back(nullptr), size(0) {}

LinkedList::~LinkedList()
{
    while(!isEmpty())
        popFront();
}

void LinkedList::pushBack(int val)
{
    Node* t = new Node();
    t->val = val;
    t->next = nullptr;

    if(!front) //if there is no list make t front and back
        front = back = t;
    else
    {
        back->next = t;
        t->prev = back;
        back = t;
    }
    size++;
}

void LinkedList::popBack()
{
    if(back)
    {
        if(front == back)
        {
            delete back;
            back = front = nullptr;
        }
        else
        {
            Node* t = back->prev;
            t->next = nullptr;
            delete back;
            back = t;
        }
        size--;
    }
}

void LinkedList::pushFront(int val)
{
    Node* t = new Node();
    t->val = val;
    t->prev = nullptr;

    if(!front)
        front = back = t;
    else
    {
        front->prev = t;
        t->next = front;
        front = t;
    }
    size++;
}

void LinkedList::popFront()
{
    if(front)
    {
        if(front == back)
        {
            delete front;
            front = back = nullptr;
        }
        else
        {
            Node* t = front->next;
            t->prev = nullptr;
            delete front;
            front = t;
        }
        size--;
    }
}

int LinkedList::getBack()
{
    return back->val;
}

int LinkedList::getFront()
{
    return front->val;
}

bool LinkedList::isEmpty()
{
    return (!size);
}

This is pretty similar to the code for the Single Linked List that we went over in class, but it makes it so much easier to popBack. Instead of having to start at the front of the list and looping through every node to get to the one before the end, you can just put Back->prev into a temp pointer.

The only "downside" of this is that you do have one more member variable to keep track of and you need to be setting the prev pointer to null when you popFront.

Now that that part's done, time to attempt an Iterator!

No comments:

Post a Comment