c++ - 循环依赖问题链表

标签 c++ linked-list nodes circular-dependency

问题介绍:我正在编写一个程序,使用链表跟踪机场的飞行路径。例如如果数据集是

(Austin - Dallas, Dallas - Houston)

然后你试着找航类

(Austin - Houston) 

它会计算出你需要走的飞行路径:

(Austin - Dallas - Houston)

我的解决方案的工作方式(如果我能弄清楚如何做到这一点)是我有一个由 OuterNode 组成的外部链表,每个链表都包含一个内部链表的航类。 内部链表由 InnerNode 组成,其中包含指向外部节点(也称为飞行目的地)的指针。 从理论上讲,它会使很多事情更容易迭代,而不必通过字符串不断复制数据。 在我的 header 中,我的太多东西相互依赖,无法以正确的顺序实现。 (这都在 innerlist 类的头部)

struct OuterNode {
    InnerList flights;
    int name;
    OuterNode* next;
};

struct InnerNode {
    OuterNode* dest;
    int price;
    InnerNode* next;
};
class InnerList
{
public:
    InnerList();
    ~InnerList();
    void add(InnerNode*);
private:
    InnerNode* innerhead;
};

所以基本上:

OuterNode – 需要 InnerList(还没有定义)

InnerNode – 需要 OuterNode

InnerList – 需要 InnerNode

而目前的错误是当OuterNode需要制作一个时,InnerList不存在。 我该如何解决这个问题,以便一切都能找到它需要的东西? 是否有一些创造性的模板使用或我可以用来解决这个问题的方法?

最佳答案

"Is there some creative use of templates or something that I could use to fix this?"

不需要使用模板,你可以简单地重组你的代码,并为 struct InnerNode; 引入一个前向声明

struct InnerNode;  // << forward declaration 

// Declare class InnerList first
class InnerList {
public:
    InnerList();
    ~InnerList();
    void add(InnerNode*);
private:
    InnerNode* innerhead;
};

struct OuterNode {
    InnerList flights;
    int name;
    OuterNode* next;
};

// Finally declare InnerNode completely
struct InnerNode {
    OuterNode* dest;
    int price;
    InnerNode* next;
};

LIVE DEMO


请注意:

除了制作自己的链表结构,您还可以考虑使用 std::list<InnerNode*> flights; 甚至是 std::vector<InnerNode*> flights; 您的成员(member) OuterNode结构。
尽管这些解决方案需要处理 InnerNode 的实例是的,通过内存管理,std::list<std::shared_ptr<InnerNode>>std::vector<std::shared_ptr<InnerNode>> 看起来是正确的方法。

关于c++ - 循环依赖问题链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852513/

相关文章:

c++ - 使用枚举类和运算符重载分隔 header

c - 使用scanf()输入字符的问题

c - 为什么这个简单的链表程序会出现段错误?

node.js - Express 和 Hihttp2 不适合我

Javascript for 循环每隔一段时间工作一次

java - 没有尾部字段的 LinkedList 陷入无限循环

c++ - 使用模板对象操作

c++ - 正确编写引用的比较运算符

c++ - 编译错误递归链表

c++ - 给定一个整数 N,大于 N 且只有 0 或 1 的最小整数是多少?