dingovo1
dingovo1

Reputation: 11

create a doubly linked list in C++

I'm creating a programme that needs to read data from a spreadsheet in CSV form and assigns it to a doubly linked list in C++.I have created a singly linked list but I'm at a loss as to how to use this idea to make a doubly linked list. I understand you require a previous pointer but I am unsure as to actually implementing the code.

code for my singly linked list: to add to the list:

if (!m_head)
{
    m_head = new Node(name, reference,latitude,longitude);
}
else
{
    Node *current = m_head;
    while (current->getNext() != 0)
    {
        current = current->getNext();
    }
    current->setNext(new Node(name, reference,latitude,longitude));
}

please note: Node is a separate class to store data about the node e.g. name.

Upvotes: 0

Views: 1153

Answers (1)

alessalessio
alessalessio

Reputation: 1234

Each List Node must a have a pointer to the previous and to the next List Node. The List is then the container of List Nodes , linked together as a chain.

struct ListNode;

typedef struct ListNode {
    struct ListNode *next;
    struct ListNode *prev;
    void *value;
} ListNode;

typedef struct List {
    int count;
    ListNode *first;
    ListNode *last;
} List;

You need then to implement the methods push and pop accordingly. The tricky part is the remove method. Store the two pointers of the previous and next Node that you want to delete, and then assign them accordingly to the previous and following node:

ListNode *after = node->next;
ListNode *before = node->prev;
after->prev = before;
before->next = after;

This article may help you, full code and explanation

http://c.learncodethehardway.org/book/ex32.html

Upvotes: 2

Related Questions