Appending to a doubly linked list

I'm trying to append an array of characters to a doubly linked list and this is what I have so far. I'm confused about how to get my list to display correctly when I call display_list() in main() since nothing prints. I know I must not be appending correctly, I'm just having a hard time wrapping my head around what to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    //Get_node function.
    Node* get_node(char entry, Node* forward, Node* backward) {
        Node* temp;
        temp = new Node;
        temp->data = entry;
        temp->next = forward;
        temp->back = backward;
        
        return temp;
    }

    //Append function to add new number to the linked list.
    void append(char entry) {
        Node* newNode;
        newNode = new Node;

        if (!head) {
            newNode = get_node(entry, nullptr, nullptr);
        }
        newNode->next = get_node(entry, nullptr, newNode->back);
    }

    //Display contents of the list.
    void display_list() {
        Node* nodePtr;
        nodePtr = head;

        while (nodePtr) {
            cout << nodePtr->data << " ";
            nodePtr = nodePtr->next;
        };
        cout << endl;
    }
};
Last edited on
understand the purpose of your functions
get_node() creates a node, so doing newNode = new Node; in append() is wrong, it is not its responsibility and causes a memory leak

now, you check if(!head) but then never change head
head always remains null, so your list is empty


¿where append() should add the new item? ¿at the start? ¿at the end? ¿somewhere in the middle?
Last edited on
That makes sense.
In the case of this program I want to keep appending to the end of the list.
I adjusted the append function to this...
1
2
3
4
5
6
7
    //Append function to add new number to the linked list.
    void append(char entry) {
        if (!head) {
            head = get_node(entry, nullptr, nullptr);
        }
        head->next = get_node(entry, nullptr, head->back);
    }

However, my output isn't what I want it to be.
draw a diagram
head is your first element
head->next is your second element
¿how do you reach the last element? ¿do you perhaps have a tail?

¿what value is in head->back?
also, take care to not dereference a null pointer.
Topic archived. No new replies allowed.