在链接列表中交换两个节点

时间:2009-12-04 16:04:03

标签: .net .net-2.0 linked-list

我遇到了一个简单的“问题”:在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

足够?

2 个答案:

答案 0 :(得分:2)

怎么样:

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

另一方面,任何已经引用节点的内容都会看到更改,可能不是您想要的。当然,任何已经引用节点的东西最终都会使用我的第一种方法看到不再属于列表的节点......

答案 1 :(得分:2)

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