| using System; |
| using System.Collections.Generic; |
| using System.Linq; |
| using System.Text; |
| |
| namespace Linked_Lists |
| { |
| class Node<T> |
| { |
| public T Data { get; set; } |
| public Node<T> Next { get; set; } |
| public Node<T> Prev { get; set; } |
| } |
| |
| class LinkedList<T> |
| { |
| private Node<T> Head; |
| private Node<T> Tail; |
| public int Size { get; private set; } |
| |
| public LinkedList() |
| { |
| Head = null; |
| Tail = null; |
| Size = 0; |
| } |
| |
| public void add(T elem) |
| { |
| Node<T> newNode = new Node<T>() { Data=elem, Next=null, Prev=Tail }; |
| if (Head == null) //elem is the first element |
| { |
| Head = newNode; |
| Tail = Head; |
| } |
| else |
| { |
| Tail.Next = newNode; |
| Tail = Tail.Next; |
| Tail.Next = null; |
| } |
| Size++; |
| } |
| |
| public T at(int index) |
| { |
| if (index >= Size || index < 0) |
| { |
| throw new IndexOutOfRangeException(); |
| } |
| else |
| { |
| Node<T> cnt = Head; |
| for (; index!=0; index--) |
| { |
| cnt = cnt.Next; |
| } |
| return cnt.Data; |
| } |
| |
| } |
| |
| |
| public void removeValue(T elem) |
| { |
| remove(indexOf(elem)); |
| } |
| |
| public void remove(int index) |
| { |
| if (index >= Size || index < 0) |
| { |
| throw new IndexOutOfRangeException(); |
| } |
| else |
| { |
| Node<T> cnt = Head; |
| //Find the deletion point |
| for (; index != 0; index--) |
| { |
| cnt = cnt.Next; |
| } |
| //cnt is the node to delete. |
| //Three cases to handle, based on where the node is located (head, tail, or middle). |
| if (cnt == Head) |
| { |
| Head = Head.Next; |
| } |
| else if (cnt == Tail) |
| { |
| Tail = Tail.Prev; |
| Tail.Next = null; |
| } |
| else |
| { |
| cnt.Next.Prev = cnt.Prev; |
| cnt.Prev.Next = cnt.Next; |
| cnt = null; |
| } |
| Size--; |
| } |
| } |
| |
| public int indexOf(T elem) |
| { |
| int index = -1; //Start at an invalid index. Return this unless we find a match for elem. |
| |
| Node<T> cnt = Head; |
| int cntIndex = 0; |
| while (cnt != null) |
| { |
| if (cnt.Data.Equals(elem)) |
| { |
| index = cntIndex; |
| cnt = null; |
| } |
| else |
| { |
| cnt = cnt.Next; |
| cntIndex++; |
| } |
| } |
| return index; |
| } |
| |
| ~LinkedList() |
| { |
| Head = null; |
| Tail = null; |
| } |
| } |
| } |