-
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study13 { public class Stack<T> : IEnumerable { private Node<T> top; public Stack() { } public void Push(T data) { if (this.top == null) { top = new Node<T>(data); } else { var node = new Node<T>(data); node.next = top; top = node; } } public T Pop() { if (this.top == null) { throw new ApplicationException("empty"); } else { var data = top.data; top = top.next; return data; } } public int Count() { if (top == null) { return 0; } else { int cnt = 1; Node<T> current = top; while (current.next != null) { cnt++; current = current.next; } return cnt; } } public IEnumerator GetEnumerator() { if (top == null) throw new Exception("empty"); var current = top; while (current != null) { yield return current; current = current.next; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study13 { public class App { public App() { Stack<int> stack = new Stack<int>(); stack.Push(3); stack.Push(5); stack.Push(7); stack.Push(9); int a = stack.Count(); Console.WriteLine(a); foreach (Node<int> node in stack) { Console.WriteLine(node.data); } } } }