Store the address of previous node into the “prev” section of current node(将前一个节点的地址存储到当前节点的“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"部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将前一个节点的地址存储到当前节点的“prev"部分
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
