How to do a “Pointer to Pointer” in C#?

2020-05-01 09:28发布

I have a data structure similar to a List, but I could not use any built-in containers (List<> etc.). I'd like to keep a "pointer to pointer" aka "tail", which point to the tail of this list. It should like this in 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);
  }
}

How to implement this in C#? Thanks!

标签: c# c++ pointers
2条回答
女痞
2楼-- · 2020-05-01 09:45

You're right, C# cannot (safely) implement a pointer-to-pointer. As a result cute code like yours is not possible. This is the best I can do.

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;
  }
}

It's not bad, is it? Almost exactly the same length and (I would argue) slightly easier to understand.

There are powerful features in C++ that are not available in C#, but in my experience C# is a significantly more productive language, even for low level code like this.

If you have some other code that you think will not yield to this kind of simple translation please post and we'll see what we can do.

查看更多
成全新的幸福
3楼-- · 2020-05-01 09:51

How about using a LinkedList instead of the List<>...?

查看更多
登录 后发表回答