我如何能够访问双向链表中的嵌套结构

How might I be able to access a nested struct within a doubly linked list?

本文关键字:嵌套 结构 双向链表 何能够 访问      更新时间:2023-10-16

我正在尝试使用带有标题结构的双向链表。我相信标头结构只是应该保存列表中已创建的结构数量以及第一个和最后一个节点。现在我看到两个问题。一个是将标头结构连接到后续结构,第二个是访问我在列表节点(哨兵(中的嵌套结构。如果有人能阐明我可能做错了什么,将不胜感激。代码如下。

#include <iostream>
using namespace std;
typedef struct sentry sentry; 
struct stud{
    string name;
    char grade;
};
struct slist {
    int length;
    sentry *first;
    sentry *last;
};
struct sentry {
    slist *list;
    sentry *next;
    sentry *prev;
    stud *student;
};
int main(int argc, char** argv) {
    slist list;
    sentry *n;
    n = new sentry;
    // Full initialization of the header node.
    list.first = n;
    list.last = n;
    list.length = 0;
    n->prev = NULL;
    n->next = NULL;
    n->list = list->last;
    n->student->name = "test";
    n->student->grade = 'A';
    cout << n->student->name << 'n';
    cout << n->student->grade << 'n';
    return 0; 
}

为什么不修改结构哨兵以不包含slist *list?为什么sentryslist之间需要双向关系这使得维护、读取和更新哨兵列表中的值变得乏味。没关系,解除堆上的内存以避免内存泄漏。为什么不让slist(标题(只有有关sentry的信息。通过这种方式,您可以消除sentryslist之间双重绑定的复杂性。

 struct sentry {
        sentry *next;
        sentry *prev;
        stud *student;
 };