0

I am trying to make a double linked list. Function push(int x) should add a node to the list and make the correct link. I use:

class Node {
public:
    int value;
    Node* next;
    Node* prev;

public:
    Node() {}
    void set_value(int x) { value = x; }
    void set_next(Node* x) { next = x; }
    void set_prev(Node* x) { prev = x; }

    Node* get_next() { return next; }
    Node* get_prev() { return prev; }        
};

class deque {
    public:
        Node* head;
        Node* tail;
    public:
        deque() { head = NULL; tail = NULL; }
        void push(int x) {
             Node* n = new Node();
             n->set_value(x);
             n->set_next(NULL);
             n->set_prev(NULL);

             Node* t = head; //link to the next node           
             if (t == NULL) {
                 head = n; 
             } else {
                 while (t->get_next() != NULL) {
                       t = t->get_next();
                 }
                 t->set_next(n);
             }
        }     
};

As I have tested the part that connects a node to the next one works fine but I am having some troubles connecting the node to the previous one. One that comes in mind is a variation of the first one:

Node* t = tail;             
if (t == NULL) {
    tail = n; 
} else {
    while (t->get_prev() != NULL) {
          t = t->get_prev();
    }
    t->set_prev(n);
}

But by using this, the tail node is always the current n node if only the node n is the one and only node in the queue... What should I do? thanks a lot

1
  • Why not simply using something like n->set_prev(tail); tail->set_next(n); tail = n; with proper NULL-pointer verification? Commented Jan 25, 2015 at 12:03

1 Answer 1

4

Drawing always helps with such data structures. What you have currently:

enter image description here

You correctly set t's next with: t->set_next(n);. What is missing is the arrow underneath it, and it's: n->set_prev(t).

In general, when dealing with doubly-linked lists, a call to set_next should always (most of the time) be accompanied by a call to set_prev on set_next's argument. It's because of the doubly-linked list's property:

x->next == y implies y->prev == x, and y->prev == x implies x->next == y.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.