【问题标题】:using ref to delete Node in the middle of a linked list, given only access to that node使用 ref 删除链表中间的节点,只允许访问该节点
【发布时间】:2016-05-19 09:52:38
【问题描述】:

我有办法。所以我不需要帮助,但我有一个问题。此代码有效:

public void Delete(ref Node n)
{
    n = n.next;
}

LinkedList list = new LinkedList();
list.AddTail(4);
list.AddTail(3);
list.AddTail(2);
list.AddTail(1);
list.AddTail(0);

list.Delete(ref list.head.next.next);

但是这段代码没有:

Node n = list.head.next.next;
list.Delete(ref n);

为什么?

编辑:

public class Node
{
    public int number;
    public Node next;

    public Node(int number, Node next)
    {
        this.number = number;
    }
}

【问题讨论】:

  • 它给出了什么错误?
  • 在什么情况下不起作用?
  • 不给出任何错误。它只是没有做任何事情。
  • 你用的是什么LinkedList?
  • 认为 它不起作用,因为在第一种情况下,您正在更改 list.head.nextnext 属性,但在第二种情况下,您只是在更改您的节点局部变量n 正在引用。

标签: c# .net linked-list ref


【解决方案1】:

当你打电话时

list.Delete(ref list.head.next.next);

您将引用(指针)更改为字段 List.next。

但是如果你打电话

list.Delete(ref n);

你改变了局部变量的引用(指针)。

试着内联你的代码:

list.Delete(ref list.head.next.next);

看起来像

list.head.next.next = list.head.next.next.next;

但是

Node n = list.head.next.next; 
list.Delete(ref n);

看起来像

Node n = list.head.next.next; 
n = n.next;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-26
    • 2022-01-05
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多