简体   繁体   English

如何在 C++ 中实现元素可以是整数或链表本身的链表?

[英]How to implement a linked list which elements can be integers or linked lists themselves in C++?

Assume I have a linked list, in which its elements can be integers or linked lists themselves.假设我有一个链表,其中的元素可以是整数或链表本身。 I also have a method named add_last .我还有一个名为add_last的方法。 How can I implement such a linked list?如何实现这样的链表?

For example:例如:

LL *l = new LL();
l->add_last(1); 
l->add_last(2);

LL *l1 = new LL();
l1->add_last(3);
l1->add_last(4);

l1->add_last(l);

The expected output for l1 should be [[3, 4], 1, 2] . l1的预期 output 应该是[[3, 4], 1, 2]

[3, 4] is considered as an element, 1 is an element, and 2 is an element. [3, 4]被认为是一个元素, 1是一个元素, 2是一个元素。

In the end, the list has 3 elements, in which 1st node is a list, 2nd node is an integer, and 3rd node is also an integer.最后,列表有3个元素,其中第一个节点是一个列表,第二个节点是integer,第三个节点也是一个integer。

Consider using structs with the various data types as members, and overloaded parameterized constructors.考虑使用具有各种数据类型的结构作为成员,并使用重载的参数化构造函数。 It would be inefficient but I believe there isn't a way to do this on C++.这将是低效的,但我相信在 C++ 上没有办法做到这一点。

You can use template classes so that your code works with any class but the linked list itself would still have only one class.您可以使用模板类,以便您的代码适用于任何 class,但链表本身仍然只有一个 class。

You could define a base node class with a next pointer and a node type, and define an inherited class that is the base class plus an integer, and define an inherited class that is the base class plus a pointer to a base class node. You could define a base node class with a next pointer and a node type, and define an inherited class that is the base class plus an integer, and define an inherited class that is the base class plus a pointer to a base class node. add_last() would select which inherited class node to use based on input and set the base node type based on what type of node it is (integer or pointer to node). add_last() 将 select 继承 class 节点以根据输入使用并根据它是什么类型的节点(整数或指向节点的指针)设置基本节点类型。 An output list function would select which inherited class node to use based on the node type.一个 output 列表 function 将 select 继承 ZA2F2ED4F8EBC2CBB14C21A29DC40 节点类型的 ZA2F2ED4F8EBC2CBB14C21A29DC40 节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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