【问题标题】:How to do a "Pointer to Pointer" in C#?如何在 C# 中做一个“指向指针的指针”?
【发布时间】:2014-06-05 07:28:50
【问题描述】:

我有一个类似于 List 的数据结构,但我不能使用任何内置容器(List 等)。我想保留一个“指针指针”又名“尾巴”,它指向这个列表的尾部。在 C++ 中应该是这样的:

class MyList {
  Node* head;
  Node** tail;  // tail is just a pointer to the "next" pointer of the end of the list.
  MyList() {
    head = null;
    tail = &head;
  }
  bool isEmpty() {
    return head == null;
  }
  void add(int val) {
    *tail = new Node();
    (*tail)->val = val;
    tail = &((*tail)->next);
  }
}

如何在 C# 中实现这一点?谢谢!

【问题讨论】:

  • 没有必要用指针来做,引用就足够了。但是,你为什么还要这样做?你应该解释你试图解决的问题,因为你很可能在想这个错误。将 C++ 音译为 C# 通常是个坏主意。 List[List.Count - 1] 有什么问题?另外,如果你想要一个链表,为什么不使用内置的LinkedList? :)
  • 不要把苹果和橙子混在一起
  • 啊.. 好了。谢谢。更清晰。
  • @Luaan 如何处理参考文献?
  • 一般我认为最简单的方法是让节点本身包含对下一个节点的引用

标签: c# c++ pointers


【解决方案1】:

使用LinkedList 代替列表怎么样...?

【讨论】:

  • 谢谢。但我的例子只是我的问题的抽象,它是相似的,但又不一样。在实际情况下,我无法使用任何这些内置容器。
  • @JASON - 您是否介意更深入地了解您想要做什么而您(认为您)无法使用内置容器做的事情?
【解决方案2】:

你是对的,C# 不能(安全地)实现指针对指针。因此,像你这样可爱的代码是不可能的。这是我能做的最好的了。

public class Node {
  public Node next;
  public int val;
}
class MyList {
  Node head = null;
  Node tail = null;
  public MyList() { }
  bool isEmpty() {
    return head == null;
  }
  void add(int val) {
    if (isEmpty())
      head = tail = new Node();
    else {
      tail.next = new Node();
      tail = tail.next;
    }
    tail.val = val;
  }
}

还不错吧?几乎完全相同的长度,并且(我认为)更容易理解。

C++ 中有一些 C# 中没有的强大功能,但根据我的经验,C# 是一种效率更高的语言,即使对于像这样的低级代码也是如此。

如果您认为其他一些代码不会接受这种简单的翻译,请发布,我们会看看我们能做些什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2021-08-14
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多