如何做一个“指针指向指针”在c#

本文关键字:指针 何做一 | 更新日期: 2023-09-27 18:06:54

我有一个类似于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#

用LinkedList代替List<>…怎么样?

你是对的,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#是一种效率更高的语言,即使对于像这样的低级代码也是如此。

如果你有其他代码,你认为不会屈服于这种简单的翻译,请发布,我们会看看我们能做什么。