交换LinkedList中的两个节点
我遇到了一个简单的“问题”:交换 LinkedList (.NET 2) 中的两个节点,我怎样才能以“最佳”方式做到这一点。谢谢!
Dim label1 As New Label()
Dim label2 As New Label()
'... some code
Dim testList As New LinkedList(Of Label)
'... some code
Dim node1 As LinkedListNode(Of Label) = testList.Find(label1)
Dim node2 As LinkedListNode(Of Label) = testList.Find(label2)
If ??? Then
' exchange two nodes
End If
够了吗
node1.Value = label2
node2.Value = label1
?
I encountered a simple "problem": Exchange two nodes in a LinkedList (.NET 2) How can I do it in a "optimal" way. Thanks!
Dim label1 As New Label()
Dim label2 As New Label()
'... some code
Dim testList As New LinkedList(Of Label)
'... some code
Dim node1 As LinkedListNode(Of Label) = testList.Find(label1)
Dim node2 As LinkedListNode(Of Label) = testList.Find(label2)
If ??? Then
' exchange two nodes
End If
is the
node1.Value = label2
node2.Value = label1
sufficient?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道实现,但如果您的节点只有一个值(除了下一个和上一个链接之外),您只需交换这些值即可。
I don't know the implementation, but if your nodes have simply one value (in addition to the next and previous links), you can just swap the values.
怎么样:
这是四个 O(1) 操作,并且无论节点位于列表的开头还是结尾都会起作用。唯一的问题是,如果 node1 == node2 它将添加两个新节点,删除现有节点,然后在尝试再次删除它时抛出异常。显然,如果您的算法确保它们从一开始就不同,那么这不是问题......
编辑:Doh。 MSDN 文档误导我认为
Value
是只读的。 (它说:“获取节点中包含的值” - 而不是“获取或设置 [...]。”实际上它是可写的,所以你可以做:另一方面,任何已经拥有对节点的引用将看到更改,这可能不是您想要的当然,任何已经拥有对节点的引用的东西最终都会看到不再是其一部分的节点。使用我的第一种方法的列表......
How about:
This is four O(1) operations, and will work whether the nodes are at the start or end of the list. The only problem is that if node1 == node2 it will add two new nodes, remove the existing one, and then throw an exception as it tries to remove it again. Obviously this isn't a problem if your algorithm makes sure they're different to start with...
EDIT: Doh. The MSDN docs misled me into thinking that
Value
is read-only. (It says: "Gets the value contained in the node" - rather than "Gets or sets [...]." Actually it's writable, so you could do:On the other hand, anything that already has a reference to the nodes will see the change, which may not be what you want. Of course, anything that already has a reference to the nodes will end up seeing nodes which are no longer part of the list using my first approach...