From 353f045d4bcd4f3fedd968b14bea8aa1b2c01418 Mon Sep 17 00:00:00 2001 From: Anastasiya Holubeva Date: Fri, 10 Aug 2018 21:00:04 +0300 Subject: [PATCH] Add stack implementation --- MyStack.cs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 MyStack.cs diff --git a/MyStack.cs b/MyStack.cs new file mode 100644 index 0000000..a6ccb3b --- /dev/null +++ b/MyStack.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Stack +{ + + public class Node + { + public Node(T data) + { + Data = data; + } + public T Data { get; set; } + public Node Next { get; set; } + } + public class NodeStack : IEnumerable + { + Node head; + int count; + public bool IsEmpty + { + get { return count == 0; } + } + public int Count + { + get { return count; } + } + + public void Push(T item) + { + Node node = new Node(item); + node.Next = head; + head = node; + count++; + } + public T Pop() + { + if (IsEmpty) + throw new InvalidOperationException("Стек пуст"); + Node temp = head; + head = head.Next; + count--; + return temp.Data; + } + public T Peek() + { + if (IsEmpty) + throw new InvalidOperationException("Стек пуст"); + return head.Data; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable)this).GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + Node current = head; + while (current != null) + { + yield return current.Data; + current = current.Next; + } + } + + } +}