将前一个节点的地址存储到当前节点的“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;
}
}
相关文章