Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Collections;
- namespace Queue
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- Queue<string> queue = new Queue<string>();
- queue.Enqueue("tom");
- queue.Enqueue("sam");
- queue.Enqueue("max");
- queue.Enqueue("kirill");
- foreach(string s in queue)
- {
- Console.WriteLine(s);
- }
- Console.WriteLine();
- string header = queue.First();
- Console.WriteLine($"первый элемент: {header}");
- Console.WriteLine();
- string firstitem = queue.Dequeue();
- Console.WriteLine($"извлеченный элемент: {firstitem}");
- Console.WriteLine();
- header = queue.First();
- Console.WriteLine($"первый элемент: {header}");
- Console.WriteLine();
- foreach(string s in queue)
- {
- Console.WriteLine(s);
- }
- }
- public class Node<T>
- {
- public Node(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public Node<T> Next { get; set; }
- }
- public class Queue<T> : IEnumerable<T>
- {
- Node<T> head;
- Node<T> tail;
- int count;
- //добавление в очередь
- public void Enqueue(T data)
- {
- Node<T> node = new Node<T>(data);
- Node<T> tempnode = tail;
- tail = node;
- if (count == 0)
- {
- head = tail;
- }
- else
- {
- tempnode.Next = tail;
- }
- count++;
- }
- //удаление из очереди
- public T Dequeue()
- {
- if(count == 0)
- {
- throw new InvalidOperationException("очередь пуста");
- }
- T output = head.Data;
- head = head.Next;
- 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)
- {
- 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;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement