I am trying to create a generic doubly linked list , and I am having trouble getting my head around it. Does anyone have an example of a very simple implementation of Doubly Linked List using C#?
Thanks
Below a simple generic double-linked list supporting Add()
, an indexer and ToString()
- the rest is left as an exercise for the reader - this should give you an idea.
public class LinkedList<T>
{
protected LinkedListNode<T> root = null;
protected LinkedListNode<T> last = null;
public LinkedList()
{
}
public string ToString()
{
StringBuilder sb = new StringBuilder();
var node = root;
while (node != null)
{
sb.Append("{ " + node.Data.ToString() + " } ");
node = node.Next;
}
return sb.ToString();
}
public T this[int index]
{
get
{
var node = GetAt(index);
if(node == null)
throw new ArgumentOutOfRangeException();
return node.Data;
}
set
{
var node = GetAt(index);
if (node == null)
throw new ArgumentOutOfRangeException();
node.Data = value;
}
}
private LinkedListNode<T> GetAt(int index)
{
var current = root;
for(int i=0;i<index;i++)
{
if (current == null)
return null;
current = current.Next;
}
return current;
}
public void Add(T data)
{
if (root == null)
{
root = new LinkedListNode<T>(data);
last = root;
}
else
{
last.Next = new LinkedListNode<T>(data);
last.Next.Previous = last;
last = last.Next;
}
}
}
public class LinkedListNode<T>
{
public T Data {get;set;}
public LinkedListNode(T data)
{
Data = data;
}
public LinkedListNode<T> Next { get; set; }
public LinkedListNode<T> Previous { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With