Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace Generics
- {
- public class Node<T>
- {
- public Node(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public Node<T> Previous { get; set; }
- public Node<T> Next { get; set; }
- }
- public class DoublyLinkedList<T> : IEnumerable<T>
- {
- Node<T> head;
- Node<T> tail;
- int count;
- public void Add (T data)
- {
- Node<T> node = new Node<T>(data);
- if (head == null)
- head = node;
- else
- {
- tail.Next = node;
- node.Previous = tail;
- }
- tail = node;
- count++;
- }
- public void AddFirst(T data)
- {
- Node<T> node = new Node<T>(data);
- Node<T> temp = head;
- node.Next = temp;
- head = node;
- if (count == 0)
- tail = head;
- else
- temp.Previous = node;
- count++;
- }
- public bool Remove(T data)
- {
- Node<T> current = head;
- while (current != null)
- {
- if (current.Data.Equals(data))
- {
- break;
- }
- current = current.Next;
- }
- if(current!=null)
- {
- if(current.Next!=null)
- {
- current.Next.Previous = current.Previous;
- }
- else
- {
- tail = current.Previous;
- }
- if(current.Previous!=null)
- {
- current.Previous.Next = current.Next;
- }
- else
- {
- head = current.Next;
- }
- count--;
- return true;
- }
- return false;
- }
- public int Count { get { return count; } }
- public bool IsEmpty { get { return count == 0; } }
- public void Clear()
- {
- head = null;
- tail = null;
- count = 0;
- }
- public bool Contains(T data)
- {
- Node<T> current = head;
- while (current != null)
- {
- if (current.Data.Equals(data))
- return true;
- current = current.Next;
- }
- return false;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable)this).GetEnumerator();
- }
- IEnumerator<T> IEnumerable<T>.GetEnumerator()
- {
- Node<T> current = head;
- while (current != null)
- {
- yield return current.Data;
- current = current.Next;
- }
- }
- public IEnumerable<T> BackEnumerator()
- {
- Node<T> current = tail;
- while (current != null)
- {
- yield return current.Data;
- current = current.Previous;
- }
- }
- public T[] ShowList()
- {
- if (count == 0)
- {
- throw new Exception("The List is empty");
- }
- else
- {
- Node<T>[] result = new Node<T>[count];
- Node<T> node = head;
- for (int i = 0; i < count; ++i) {
- result[i] = node;
- node = node.Next;
- }
- return result;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement