将前一个节点的地址存储到当前节点的“prev"部分 [英] Store the address of previous node into the “prev” section of current node

查看:23
本文介绍了将前一个节点的地址存储到当前节点的“prev"部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我使用名为 listrec 的结构定义了我的节点.所以每个节点有3个部分:prev(用来存储上一个节点的地址)、value(用来存储值)和next(用来存储下一个节点的地址).

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;

        }
    }

但是我不知道如何将前一个节点的地址存储到当前节点的prev中.

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.

由于每次创建新节点时,tail 的位置都会移动,并且 head 始终指向第一个节点……我如何才能将前一个节点的地址存储到当前节点的prev"部分中?

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?

推荐答案

新建节点,设置成员,将地址存入next并更新tail

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;
    }
}

这篇关于将前一个节点的地址存储到当前节点的“prev"部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆