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

前端 未结 2 807
说谎
说谎 2021-01-29 01:10

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

2条回答
  •  执笔经年
    2021-01-29 01: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.

提交回复
热议问题