ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Stack 순서도
    알고리즘/수업내용 2022. 7. 4. 12:33

    Stack push
    Stack pop
    Stack count
    Stack print


    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);
                }
            }
        }
    }

    '알고리즘 > 수업내용' 카테고리의 다른 글

    Queue 순서도  (0) 2022.07.04
    링크드 리스트  (0) 2022.07.01
Designed by Tistory.