Reputation: 80
I'm trying to implement a double linked list in c# but I've never used pointers before and cannot find a solution. I'm trying to create the node class which will hold a single item and pointers to the adjacent nodes.
// single elements in the list
unsafe class Node { Node* previous}
{
public int data;
public Node *next;
public Node *prev = *previous;
}
I keep getting the error in the title and I don't know how to fix it.
Upvotes: 2
Views: 114
Reputation: 1228
As CrowCoder stated you do not and should not use pointers in C# for this implementation. This code should get you started:
internal class LLNode {
internal int data;
internal LLNode prev;
internal LLNode next;
public LLNode (int d) {
data = d;
prev = null;
next = null;
}
}
Upvotes: 0
Reputation: 1063569
You don't need unasnaged pointers or unsafe
here at all. Because Node
is a class, when you use Node
as a parameter, field, variable etc - this is a reference to a Node
instance. A reference here means "managed pointer" - i.e. like a pointer, but with full GC support and type safety, etc. So all you need is Node
:
class Node
{
public int Data {get;set;}
public Node Next {get;set;} // Next/Previous might want "private set" if
public Node Previous {get;set;} // you are going to change them via methods
}
More specifically, you cannot readily take an unmanaged pointer to a class
in C# - a Node*
- that simply isn't a thing you can do. You can do that with struct
, but: you almost certainly shouldn't. I expect the point here is to use managed pointers, aka references, i.e. Node
, not Node*
.
Upvotes: 3