Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace DoubleLinkedListExample
- {
- public class Node<T>
- {
- public T item;
- public Node<T> next;
- public Node<T> prev;
- public Node(T data)
- {
- this.item = data;
- this.next = null;
- this.prev = null;
- }
- }
- public class DoubleLinkedList<T>
- {
- public int Size { get; set; }
- private Node<T> head;
- private Node<T> current;
- public DoubleLinkedList()
- {
- this.Size = 0;
- this.head = null;
- this.current = null;
- }
- public void Add(Node<T> element)
- {
- if (this.head == null)
- {
- this.head = element;
- this.head.prev = null;
- this.current = this.head;
- this.head.next = this.current;
- this.Size++;
- }
- else
- {
- this.current.prev = this.current;
- this.current.next = element;
- this.current = this.current.next;
- this.Size++;
- }
- }
- public void AddToHead(Node<T> element)
- {
- if (this.head == null)
- {
- this.head = element;
- this.current = this.head;
- this.head.next = this.current;
- this.Size++;
- }
- else
- {
- this.head.prev = element;
- this.head.prev.next = this.head;
- this.head = this.head.prev;
- this.head.prev = null;
- this.Size++;
- }
- }
- public T this[int index]
- {
- get
- {
- if(index >= this.Size || index<0)
- {
- throw new IndexOutOfRangeException(
- String.Format("The index is out range! (index: {0}, size: {1})", index, this.Size));
- }
- Node<T> result = this.head;
- result = GetElementOfPosition(index, result);
- return result.item;
- }
- }
- public void InsertAt(Node<T> element, int position)
- {
- if (position > this.Size || position < 0)
- {
- throw new IndexOutOfRangeException(
- String.Format("The position is out range! (pos: {0}, size: {1})", position, this.Size));
- }
- if (position == this.Size)
- {
- Add(element);
- }
- else
- {
- Node<T> currentAtPosition = this.head;
- currentAtPosition = GetElementOfPosition(position - 1, currentAtPosition);
- Node<T> nextToCurrentAtPosition = currentAtPosition.next;
- currentAtPosition.next = element;
- element.next = nextToCurrentAtPosition;
- this.Size++;
- }
- }
- private Node<T> GetElementOfPosition(int index, Node<T> result)
- {
- for (int i = 0; i < index; i++)
- {
- result = GetNext(result);
- }
- return result;
- }
- private Node<T> GetNext(Node<T> element)
- {
- Node<T> result = element.next;
- return result;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement