Here is the code to create a doubly link list in C#.
It supports insert/add, traverse (backward/forward), Contains, Index of and delete operations.
class DoublyListList
{
//Point to current node (last
node).
Node Current = null;
// Point to head node.
Node Head = null;
// Node class declaration.
class Node
{
public T content;
public Node next;
public Node previous;
}
///
/// Add node as current/last
node.
///
public void Add(T objconent)
{
Console.WriteLine(string.Format("*** Add Value
{0}",
objconent.ToString()));
Node objNode = new Node()
{
content = objconent
};
if (Head == null)
{
Head = objNode;
}
else
{
objNode.previous = Current;
Current.next = objNode;
}
Current = objNode;
Console.WriteLine("Content {" + objconent.ToString() + "} added.");
}
///
/// Add node as current/last
node.
///
public void AddFirst(T objconent)
{
Console.WriteLine(string.Format("*** Add Value
{0}",
objconent.ToString()));
Node objNode = new Node()
{
content = objconent
};
if (Head == null)
{
Head = objNode;
}
else
{
objNode.next = Head;
Head.previous = objNode;
}
Head = objNode;
Console.WriteLine("Content {" + objconent.ToString() + "} added.");
}
///
/// Add node as current/last
node.
///
public void AddLast(T objconent)
{
this.Add(objconent);
}
///
/// List down all elements of
linked list in forward manner.
///
private void ListNodesForward()
{
Console.WriteLine("*** List nodes in
forward manner:");
Node tempNode = Head;
while (tempNode != null)
{
Console.WriteLine(tempNode.content);
tempNode = tempNode.next;
}
}
///
/// List down all elements of
linked list in backward manner.
///
private void ListNodesBackward()
{
Console.WriteLine("*** List nodes in
backward manner:");
Node tempNode = Current;
while (tempNode != null)
{
Console.WriteLine(tempNode.content);
tempNode = tempNode.previous;
}
}
///
/// Return index of particular
node.
///
/// Index of node content.
public bool Contains(T objconent)
{
return this.IndexOf(objconent) > -1 ?
true : false;
}
///
/// Return index of particular
node.
///
/// Index of node content.
public int IndexOf(T objconent)
{
Console.WriteLine(string.Format("*** Index of
{0}:",
objconent.ToString()));
Node tempNode = Head;
int Counter = 0;
while (tempNode != null)
{
if
(tempNode.content.Equals(objconent))
{
return Counter;
}
tempNode = tempNode.next;
Counter++;
}
return -1;
}
///
/// Delete node.
///
public void Delete(T pValue)
{
Console.WriteLine(string.Format("*** Delete Value
{0}:",
pValue.ToString()));
Node tempNode = Head;
Node preNode = Head;
int Counter = 0;
while (tempNode != null)
{
if
(tempNode.content.Equals(pValue))
{
preNode.next = tempNode.next;
tempNode.next.previous = preNode;
return;
}
preNode = tempNode;
tempNode = tempNode.next;
Counter++;
}
}
public void ListNodes()
{
this.ListNodesForward();
this.ListNodesBackward();
}
}