Search code examples
c++linked-listnodes

Store the address of previous node into the “prev” section of current node


First, I defined my node using a struct called listrec. So each node has 3 parts: prev (used to store the address of the previous node), value (used to store the value), and next (used to store the address of next node).

#include <iostream>

using namespace std;

struct listrec
{
    struct listrec    *prev;
    float       value;
    struct listrec    *next;
};

listrec *head, *tail;

Then, I used a loop to initialize the linked list (based on the number of nodes requested by the user.

for (float i = 0; i < number; i++)
    {
        if (i == 0)
        {
            head = new listrec;
            head->prev = NULL;
            head->value = i;
            head->next = NULL;
            tail = head;
        }
        else
        {
            tail->next = new listrec;
            tail = tail->next;
            tail->value = i++;
            tail->next = NULL;

        }
    }

But I don’t know how to store the address of previous node into the current node’s prev.

Below is how the linked node should look like.

Since tail’s location is moving every time when a new node got created, and head is always pointed to the first node…how can I get the address of the previous node stored into the “prev” section of the current node?

enter image description here


Solution

  • Create a new node, set the members, store the address in next and update tail

    for (float i = 0; i < number; i++) {
        if (i == 0) {
            head = new listrec;
            head->prev = nullptr;
            head->value = i;
            head->next = nullptr;
            tail = head;
        } else {
            auto *newNode = new listrec;
            newNode->value = i++;
            newNode->next = nullptr;
            newNode->prev = tail;
            tail->next = newNode;
            tail = tail->next;
        }
    }