Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections;
- namespace Deque
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- Deque<string> deque = new Deque<string>();
- deque.AddFirst("alice");
- deque.AddLast("kate");
- deque.AddLast("tom");
- foreach(string item in deque)
- {
- Console.WriteLine(item);
- }
- string removedItem = deque.RemoveFirst();
- Console.WriteLine($"\n удален: {removedItem}\n");
- foreach(string item in deque)
- {
- Console.WriteLine(item);
- }
- }
- public class DoublyNode<T>
- {
- public DoublyNode(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public DoublyNode<T> Next { get; set; }
- public DoublyNode<T> Previous { get; set; }
- }
- public class Deque<T> : IEnumerable<T>//двухсязный список
- {
- DoublyNode<T> head;
- DoublyNode<T> tail;
- int count;
- //добавление элемента
- public void AddLast(T data)
- {
- DoublyNode<T> node = new DoublyNode<T>(data);
- if(head == null)
- {
- head = node;
- }
- else
- {
- tail.Next = node;
- node.Previous = tail;
- }
- tail = node;
- count++;
- }
- public void AddFirst(T data)
- {
- DoublyNode<T> node = new DoublyNode<T>(data);
- DoublyNode<T> temp = head;
- node.Next = temp;
- head = node;
- if(count == 0)
- {
- tail = head;
- }
- else
- {
- temp.Previous = node;
- }
- count++;
- }
- public T RemoveFirst()
- {
- if(count == 0)
- {
- throw new InvalidOperationException();
- }
- T output = head.Data;
- if(count == 1)
- {
- head = tail = null;
- }
- else
- {
- head = head.Next;
- head.Previous = null;
- }
- count--;
- return output;
- }
- public T RemoveLast()
- {
- if(count == 0)
- {
- throw new InvalidOperationException ();
- }
- T output = tail.Data;
- if (count == 1)
- {
- head = tail = null;
- }
- else
- {
- tail = tail.Previous;
- tail.Next = null;
- }
- count--;
- return output;
- }
- public T First
- {
- get
- {
- if(IsEmpty)
- {
- throw new InvalidOperationException();
- }
- return tail.Data;
- }
- }
- public int Count { get { return count; } }
- public bool IsEmpty { get { return count == 0; } }
- public void Clear()
- {
- head = tail = null;
- count = 0;
- }
- public bool Contains (T data)
- {
- DoublyNode<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()
- {
- DoublyNode<T> current = head;
- while(current != null)
- {
- yield return current.Data;
- current = current.Next;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment