using System.Collections.Generic;
public class DoublyLinkedList<T>
public ListNode PreviousNode
public ListNode(T element)
public ListNode(T element, ListNode prevNode)
prevNode.NextNode = this;
this.PreviousNode = prevNode;
public DoublyLinkedList()
this.head = new ListNode(item);
ListNode newNode = new ListNode(item, this.tail);
public T RemoveAt(int index)
if (index >= count || index < 0)
throw new ArgumentOutOfRangeException("Invalid index: " + index);
ListNode currentNode = this.head;
ListNode prevNode = null;
while (currentIndex < index)
currentNode = currentNode.NextNode;
RemoveListNode(currentNode, prevNode);
return currentNode.Element;
private void RemoveListNode(ListNode node, ListNode prevNode)
else if (prevNode == null)
this.head = node.NextNode;
else if (node.NextNode == null)
this.tail = node.PreviousNode;
prevNode.NextNode = node.NextNode;
public int Remove(T item)
ListNode currentNode = this.head;
ListNode prevNode = null;
while (currentNode !=null)
if (object.Equals(currentNode.Element, item))
currentNode = currentNode.NextNode;
RemoveListNode(currentNode, prevNode);
public int IndexOf(T item)
ListNode currentNode = this.head;
while (currentNode != null)
if (object.Equals(currentNode.Element, item))
currentNode = currentNode.NextNode;
public bool Contains(T item)
int index = IndexOf(item);
bool found = (index != -1);
if (index >= count || index < 0)
throw new ArgumentOutOfRangeException("Invalid index: " + index);
ListNode currentNode = this.head;
for (int i = 0; i < index; i++)
currentNode = currentNode.NextNode;
return currentNode.Element;
if (index >= count || index < 0)
throw new ArgumentOutOfRangeException("Invalid index: " + index);
ListNode currentNode = this.head;
for (int i = 0; i < index; i++)
currentNode = currentNode.NextNode;
currentNode.Element = value;
public class DoublyLinkedListTest
public static void Main()
DoublyLinkedList<string> shoppingList = new DoublyLinkedList<string>();
shoppingList.Add("Milk");
shoppingList.Remove("Milk");
shoppingList.Add("Honey");
shoppingList.Add("Olives");
shoppingList.Add("Water");
shoppingList[2] = "A lot of " + shoppingList[2];
shoppingList.Add("Fruits");
shoppingList.RemoveAt(0);
shoppingList.RemoveAt(2);
shoppingList.Add("Beer");
shoppingList.Remove(null);
Console.WriteLine("We need to buy:");
for (int i = 0; i < shoppingList.Count; i++)
Console.WriteLine(" - " + shoppingList[i]);
Console.WriteLine("Position of 'Beer' = {0}",
shoppingList.IndexOf("Beer"));
Console.WriteLine("Position of 'Water' = {0}",
shoppingList.IndexOf("Water"));
Console.WriteLine("Do we have to buy Bread? " +
shoppingList.Contains("Bread"));