简体   繁体   中英

Accessing struct within struct C++

I'm writing a C++ programm which has to work with linked list. But I can't figure out how can I access structure which is in another structure.

#include <cstddef>
#include "list.hpp"
using std::size_t;

struct list {
    struct node {
        double val;
        node* prev;
        node* next;
    };

    node* head = nullptr;
    node* tail = nullptr;
    size_t size = 0;
};

Can you explain me how it works? I have a method, but I don't know how I can use this structur in this method.

void push_back(list& l, double elem) {
    node *new_node = new node(elem);
    if (l.head==null) {
        l.head = new_node;

    }
    node *curent = l.head;
    while (curent) {
        if (!curent->next) {
            curent->next = new_node;
        }
        cur = cur->next;
    }
}

Thank you.

in this code , you have a doubly linked list

i'll try to explain the code of the push_back function .

at the beginning we have void push_back(list& l, double elem) , l is your current LinkedList whish you want to add a new element to it in queue, elem is the value of your new element .

if (l.head==null) {
    l.head = new_node;
}

if your linkedList is empty , we add the new element

exemple1 : empty LinkedList

if the linkedList is not empty

push back

this a simple code

    node *curent = l.head; // the current node is pointed to the head of the LinkedList
    while (curent->next != null) { // while current->next is not equal to null
            curent=curent->next ; // step forward to the next node
        }
        curent->next =new_node ; // add the new node to the queue of the linkedList

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM