Reputation: 7491
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!
Upvotes: 0
Views: 185
Reputation: 10863
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.
Upvotes: 1