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

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

问题描述

首先,我使用名为listrec的结构定义了我的节点.因此,每个节点包含3个部分:prev(用于存储前一个节点的地址),value(用于存储值)和next(用于存储下一个节点的地址).

  #include< iostream>使用命名空间std;struct listrec{struct listrec *上一页;浮动价值;struct listrec *下一个;};listrec *头,*尾巴; 

然后,我使用循环来初始化链表(基于用户请求的节点数.

  for(float i = 0; i< number; i ++){如果(i == 0){头=新的listrec;head->上一个= NULL;头值> i =head-> next = NULL;尾巴=头;}别的{tail-> next =新的listrec;尾巴=尾巴->下一个;尾巴>值= i ++;尾->下一个= NULL;}} 

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

下面是链接节点的外观.

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

解决方案

创建一个新节点,设置成员,将地址存储在 next 中,并更新 tail

  for(float i = 0; i< number; i ++){如果(i == 0){头=新的listrec;head->上一个= nullptr;头值> i =head-> next = nullptr;尾巴=头;} 别的 {自动* newNode = new listrec;newNode-> value = i ++;newNode-> next = nullptr;newNode->上一步=尾巴;tail-> next = newNode;尾巴=尾巴->下一个;}} 

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?

解决方案

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天全站免登陆