ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 스택 구현
    자료구조 2022. 3. 29. 14:31
    public class Stack {
        private int ptr;
        private int max;
        private int[] stk;
        
        public class EmptyStackException extends RuntimeException {
            
        }
        
        public class OverflowStackException extends RuntimeException {
            
        }
        
        public Stack(int capacity) {
            ptr = 0;
            max = capacity;
            try {
                stk = new int[max];
            }catch (OutOfMemoryError e) {
                max = 0;
            }
        }
        
        public int push(int x) throws OverflowStackException {
            if (ptr >= max) 
                throw new OverflowStackException();
            return stk[ptr++] = x;
        }
        
        public int pop() throws EmptyStackException {
            if (ptr <= 0)
                throw new EmptyStackException();
            return stk[ptr--];
        }
        
        public int peek() throws EmptyStackException { //가장 꼭대기에 저장된 값 조회
            if (ptr <= 0)
                throw new EmptyStackException();
            return stk[ptr - 1];
        }
        
        public int indexOf(int x) { //x라는 값 존재하는지 검색
            for (int i = ptr -1; i >= 0; i--) {
                if (stk[i] == x)
                    return i;
            }
            return -1;
        }
        
        public void clear() {
            ptr = 0;
        }
        
        public int capacity() {
            return max;
        }
        
        public int size() {
            return ptr;
        }
        
        public boolean isEmpty() {
            return ptr <= 0;
        }
        
        public boolean isFull() {
            return ptr >= max;
        }
        
        public void dump() { //스택 안 모든 값을 바닥에서 꼭대기까지 출력
            if (ptr <= 0)
                System.out.println("스택이 비어있습니다");
            else {
                for (int i = 0; i < ptr; i++) {
                    System.out.println(stk[i] + " ");
                }
                System.out.println();
            }
        }
    }

    '자료구조' 카테고리의 다른 글

    Array와 LinkedList의 차이  (0) 2023.01.05
    자료구조란? Data Structure  (0) 2023.01.04
    Deque(덱, 데크) - 자바  (0) 2022.08.06
    큐 구현  (0) 2022.03.29
Designed by Tistory.