【问题标题】:Exchange two nodes in LinkedList交换 LinkedList 中的两个节点
【发布时间】:2009-12-04 16:04:03
【问题描述】:

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

够了吗?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • :) 好的,Svante 是第一个提出这个想法的人。
    【解决方案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
    

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

    【讨论】:

    • 您如何看待 Dim tempNode1Val As Label = node1.Value node1.Value = node2.Value node2.Value = tempNode1Val
    • @jon,我也看到,在 XML cmets 中仅用于值 Obtains。通常写成获取或定义 :)
    • 谢谢,乔恩! “算法”比我想象的要简单:)
    猜你喜欢
    • 2018-07-17
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多