Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- namespace Fedortsov.Lab7Exc1
- {
- public class DoublyLinkedList<T>
- {
- private class Node
- {
- public T Value { get; set; }
- public Node Next { get; set; }
- public Node Previous { get; set; }
- public Node(T value)
- {
- Value = value;
- Next = null;
- Previous = null;
- }
- }
- private Node head;
- private Node tail;
- public int Count { get; private set; }
- public DoublyLinkedList()
- {
- head = null;
- tail = null;
- Count = 0;
- }
- public void AddFirst(T value)
- {
- Node newNode = new Node(value);
- if (head == null)
- {
- head = newNode;
- tail = newNode;
- }
- else
- {
- newNode.Next = head;
- head.Previous = newNode;
- head = newNode;
- }
- Count++;
- }
- public void AddLast(T value)
- {
- Node newNode = new Node(value);
- if (tail == null)
- {
- head = newNode;
- tail = newNode;
- }
- else
- {
- newNode.Previous = tail;
- tail.Next = newNode;
- tail = newNode;
- }
- Count++;
- }
- public void RemoveFirst()
- {
- if (head == null)
- {
- throw new InvalidOperationException("List is empty");
- }
- if (head == tail)
- {
- head = null;
- tail = null;
- }
- else
- {
- head = head.Next;
- head.Previous = null;
- }
- Count--;
- }
- public void RemoveLast()
- {
- if (tail == null)
- {
- throw new InvalidOperationException("List is empty");
- }
- if (head == tail)
- {
- head = null;
- tail = null;
- }
- else
- {
- tail = tail.Previous;
- tail.Next = null;
- }
- Count--;
- }
- public bool Contains(T value)
- {
- Node current = head;
- while (current != null)
- {
- if (current.Value.Equals(value))
- {
- return true;
- }
- current = current.Next;
- }
- return false;
- }
- public void Clear()
- {
- head = null;
- tail = null;
- Count = 0;
- }
- public IEnumerator<T> GetEnumerator()
- {
- Node current = head;
- while (current != null)
- {
- yield return current.Value;
- current = current.Next;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement