배열로 구현한 Stack in C#

Data structure 2020. 10. 23. 08:32
반응형
namespace Stack {
    public class App {
        public App () {
            Stack stack = new Stack (10);

            stack.Push (1);
            stack.Push (2);
            stack.Push (3);
            stack.Push (4);

            var data = stack.Pop ();
            System.Console.WriteLine (data);

        }
    }
}
using System;

namespace Stack {
    public class Stack {
        private int[] arr;
        private int top;

        public Stack (int capacity) {
            this.arr = new int[capacity];
            this.top = -1;
        }

        public void Push (int data) {
            if (this.IsFull ()) {
                throw new ApplicationException ("Stack is Full");
            } else {
                this.arr[++top] = data;
            }
        }

        public int Pop () {
            int rtnData = -1;
            if (this.IsEmpty ()) {
                throw new ApplicationException ("Stack is Empty");
            } else {

                rtnData = this.arr[this.top];
                this.arr[this.top] = 0;
                this.top--;
            }
            return rtnData;
        }

        public int Peek () {
            if (this.IsEmpty ()) {
                throw new ApplicationException ("Stack is Empty");
            } else {
                return this.arr[this.top];
            }
        }

        public bool IsFull () {
            return this.top == this.arr.Length - 1;
        }

        public bool IsEmpty () {
            return this.top == -1;
        }
    }
}
반응형

'Data structure' 카테고리의 다른 글

C# 으로 구현한 Deque (덱)  (0) 2020.11.19
단일연결리스트 (SinglyLinkedList) in c#  (0) 2020.10.23
Binary Search Tree  (0) 2020.05.29
이진 트리  (0) 2019.08.14
이진 탐색 (Binary Search)  (0) 2019.08.14
: