交换LinkedList中的两个节点

发布于 2024-08-13 02:58:35 字数 496 浏览 1 评论 0原文

我遇到了一个简单的“问题”:交换 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离旧人 2024-08-20 02:58:35

我不知道实现,但如果您的节点只有一个值(除了下一个和上一个链接之外),您只需交换这些值即可。

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.

错爱 2024-08-20 02:58:35

怎么样:

testList.AddAfter(node1, node2.Value)
testList.AddAfter(node2, node1.Value)
testList.Remove(node1)
testList.Remove(node2)

这是四个 O(1) 操作,并且无论节点位于列表的开头还是结尾都会起作用。唯一的问题是,如果 node1 == node2 它将添加两个新节点,删除现有节点,然后在尝试再次删除它时抛出异常。显然,如果您的算法确保它们从一开始就不同,那么这不是问题......

编辑:Doh。 MSDN 文档误导我认为 Value 是只读的。 (它说:“获取节点中包含的值” - 而不是“获取或设置 [...]。”实际上它是可写的,所以你可以做:

Label tmp = node1.Value
node1.Value = node2.Value
node2.Value = tmp

另一方面,任何已经拥有对节点的引用将看到更改,这可能不是您想要的当然,任何已经拥有对节点的引用的东西最终都会看到不再是其一部分的节点。使用我的第一种方法的列表......

How about:

testList.AddAfter(node1, node2.Value)
testList.AddAfter(node2, node1.Value)
testList.Remove(node1)
testList.Remove(node2)

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:

Label tmp = node1.Value
node1.Value = node2.Value
node2.Value = tmp

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文