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!
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.
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.
How about using a LinkedList instead of the List<>...?