자바로 스택 만들어보기

Kim Dong Kyun·2023년 5월 4일
1
post-thumbnail

이미지 출처 및 더 상세한 설명(영어임)

개요

요즘 알고리즘 풀면서 스택,큐 엄청 많이 사용하고 있는데, 자바로 직접 구현하려면 어떻게 해야하는지 궁금해서 해봤다.

전체 코드 아래에 Line by Line 으로 설명하는 부분이 있다.

조건

int[] 로 만든 스택이다. 다른 자료형이어도 비슷하게 구현될 듯 함!

전체 코드

private class Stack {
        private int top;
        private int[] stackArr;
        private int maxSize;

        public Stack(int size) {
            this.top = -1 ;
            this.maxSize = size;
            this.stackArr = new int[maxSize];
        }

        private void push(int data){
            if (!isFull()){
                top++;
                stackArr[top] = data;
            } else {
                throw new IllegalArgumentException("full!");
            }
        }

        private int pop(){
            if (!isEmpty()){
                int data = stackArr[top];
                top--;
                return data;
            } else {
                throw new IllegalArgumentException("empty!");
            }
        }

        private int peek(){
            if (!isEmpty()){
                return stackArr[top];
            } else {
                throw new IllegalArgumentException("empty!");
            }
        }

        private boolean isEmpty(){
            return (top == -1);
        }

        private boolean isFull(){
            return (top == maxSize - 1);
        }

    }
  

Line by line

private class Stack {
       private int top;
       private int[] stackArr;
       private int maxSize;

       public Stack(int size) {
           this.top = -1 ;
           this.maxSize = size;
           this.stackArr = new int[maxSize];
       }

Stack class를 만들고, 필드 변수를 정의한다.

  • top은 배열의 끝 인덱스이다.

  • stackArr 은 스택처럼 작동할 배열이다

  • maxSize 는 스택의 사이즈이다(배열의)

  • 생성자로 제일 끝 인덱스를 -1, 사이즈는 패러미터로 들어온 사이즈, 스택어레이도 new 키워드로 생성한다.

    private boolean isEmpty(){
              return (top == -1);
          }
    
          private boolean isFull(){
              return (top == maxSize - 1);
          }

.push(), .pop(), .peek() 등의 매서드를 정의하기 전에 스택이 꽉 찼거나 비어있을 경우를 알아내기 위한 매서드를 선언했다.

  • 스택이 비어있을 경우 top 은 초기값인 -1이다
  • 스택이 꽉 찼을경우 top의 사이즈는 maxSize의 값에서 -1 한 값과 같다.
    -> top은 인덱스로 활용되므로 size의 -1한 값과 비교한다
private void push(int data){
            if (!isFull()){
                top++;
                stackArr[top] = data;
            } else {
                throw new IllegalArgumentException("full!");
            }
        }

.push 매서드이다. 들어온 data를 스택에 넣는다.

  • 만약 배열의 길이가 꽉찼다면 에러를 던진다
  • 배열의 길이가 꽉차지 않았다면, -1로 초기화된 top을 증가시켜 인덱스로 활용한다.
  • 스택의[top] 번째 인덱스에 데이터를 할당한다.
private int pop(){
            if (!isEmpty()){
                int data = stackArr[top];
                top--;
                return data;
            } else {
                throw new IllegalArgumentException("empty!");
            }
        }

        private void peek(){
            if (!isEmpty()){
                System.out.println(stackArr[top] + "Peek!");
            } else {
                throw new IllegalArgumentException("empty!");
            }
        }

.pop(), .peek() 매서드이다. 마지막에 들어온 데이터를 반환하거나 가져온다

  • 스택의 마지막 값을 가져오거나 본다

다음 시간엔 큐도 만들어보자!

0개의 댓글