如何在C#中创建相交链表?
我正在尝试创建 2 个具有公共交集节点的链表。据我所知,这是 LinkedList 中寻找交集节点的一个非常热门的问题。我编写了以下代码,但它抛出 InvalidOperationException。
LinkedList<int> LL = new LinkedList<int>();
LL.AddFirst(5);
LL.AddFirst(4);
LL.AddFirst(3);
LL.AddFirst(2);
LL.AddFirst(1);
LinkedListNode<int> sectionNode = LL.Find(3);
LinkedList<int> LL2 = new LinkedList<int>();
LL2.AddFirst(100);
LL2.AddFirst(90);
LL2.AddFirst(80);
LL2.AddFirst(sectionNode);
有人可以指导我如何在 C# 中创建 Y 形链表吗?
I'm trying to create 2 linked list with a common intersection node. As I see this is a very hot question in LinkedList to find the intersection node. I have written following code but it throws InvalidOperationexception.
LinkedList<int> LL = new LinkedList<int>();
LL.AddFirst(5);
LL.AddFirst(4);
LL.AddFirst(3);
LL.AddFirst(2);
LL.AddFirst(1);
LinkedListNode<int> sectionNode = LL.Find(3);
LinkedList<int> LL2 = new LinkedList<int>();
LL2.AddFirst(100);
LL2.AddFirst(90);
LL2.AddFirst(80);
LL2.AddFirst(sectionNode);
Could someone please guide me how I can create a Y shaped linked list in C#.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不支持。节点跟踪其
列表
,您可以通过仅获取属性来访问它。这意味着一个节点不能同时位于两个列表中,并且只能通过删除然后添加来更改父列表。这显然是为了保护人们免受错误的影响,但它也让你想要的事情变得不可能。请注意,
LinkedList
是双向链接的,因此,如果这有效,您将必须任意选择List
和Previous
引用。您可以使用(或编写)具有不同行为的第三方实现。例如,此代码实现单链表。节点没有对其包含列表的引用,因此 Y 应该没问题。
It's not supported. The node keeps track of its
List
, which you can access through a get-only property. That means a node can't be in two lists at once, and you can only change the parent list by removing then adding.This is clearly designed to protect people from mistakes, but it also makes what you want impossible. Note that
LinkedList
is doubly linked, so you if this worked, you would have to arbitrarily pick both theList
and thePrevious
reference.You can use (or write) a third-party implementation with different behavior. For example, this code implements a singly-linked list. Nodes don't have references to their containing list, so a Y should be fine.