在struct C ++中访问struct

时间:2016-03-28 20:41:15

标签: c++ struct

我正在编写一个必须使用链表的C ++程序。但我无法弄清楚如何访问另一个结构中的结构。

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

你能解释一下它的运作方式吗?我有一个方法,但我不知道如何在这个方法中使用这个结构。

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

谢谢。

1 个答案:

答案 0 :(得分:1)

在此代码中,您有一个双向链表

我将尝试解释push_back函数的代码。

一开始我们有void push_back(list&amp; l,double elem),l是你当前的LinkedList,你想在队列中添加一个新元素,elem是你新元素的值。

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

如果您的linkedList为空,我们添加新元素

exemple1 : empty LinkedList

如果linkedList不为空

push back

这是一个简单的代码

    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