본문 바로가기
⌨️코딩테스트/백준

[JAVA/백준/10828] 스택

by Dong Ik 2022. 1. 26.
 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

스택이란 FILO (First In Last Out) 선입후출 방식을 따르는 자료구조다.

즉, 먼저 들어온 데이터가 가장 마지막에 나오며 가장 최근 들어온 데이터가 가장 빨리 나간다.

 

블럭으로 탑을 쌓으며 맨 윗 블럭부터 제거하는 방식으로 이해하면 될 것이다.

 

출처 : wikipedia

 

JAVA의 collections 프레임워크를 이용하면 스택을 쉽게 구현할 수 있지만, 구조적인 이해를 위해 배열을 이용하여 클래스로 구현해보겠다. 

 

1. Stack을 위한 클래스 선언

 

초기 사이즈는 데이터가 없다는 것을 의미하는 -1값을 넣어주었다.

class Stack {

  public int Stack_Size;
  public int Stack_arr[];


  public Stack(int size) {
    this.Stack_Size = -1;
    this.Stack_arr = new int[size];
  }
}

 

2. push

 

push는 세로운 데이터를 쌓는 작업이다.

Stack_Size를 1만큼 증가시키고 입력받은 X를 삽입한다.

public void push(int X) {
  this.Stack_Size++;
  this.Stack_arr[Stack_Size] = X;
}

 

3. pop

 

pop은 가장 위의 데이터를 제거하는 LIFO 후입 선출 방식이다.

Stack이 비었다면 -1을 return 해 주고

아니라면 스택 가장 위의 데이터를 return하고 Stack_Size를 1만큼 감소시킨다.

 

여기서 Stack_Size-- 라는 증감연산자는 앞의 데이터를 먼저 반환한 후에 연산을 한다.

만약 --Stack_Size로 계산을 했다면 증감 연산을 한 후에 데이터를 반환 했을 것이다. 

public int pop() {

  if (this.Stack_Size == -1) {
    return -1;
  }
  return this.Stack_arr[Stack_Size--];
}

 

4. size

 

스택의 사이즈를 출력하는 작업이다.

Stack_Size는 배열의 index이기 때문에 1을 더해주어 크기값을 반환해준다.

public int size() {

  return this.Stack_Size + 1;
}

 

5.empty

 

스택이 비었는지 확인하는 작업이다.

비었으면 1 아니라면 0을 반환해준다.

public int empty() {
  if (this.Stack_Size == -1) {
    return 1;
  }
  return 0;
}

 

6. top

 

가장 위의 데이터를 반환해주는 작업이다.

스택이 비었다면 -1을 반환한다.

public int top() {
    if (this.Stack_Size >= 0) {
      return this.Stack_arr[this.Stack_Size];
    }
    return -1;
  }
}

 

 

구현 완료

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

class Stack {

  public int Stack_Size;
  public int Stack_arr[];


  public Stack(int size) {
    this.Stack_Size = -1;
    this.Stack_arr = new int[size];
  }

  public void push(int X) {
    this.Stack_Size++;
    this.Stack_arr[this.Stack_Size] = X;
  }

  public int pop() {

    if (this.Stack_Size == -1) {
      return -1;
    }
    return this.Stack_arr[Stack_Size--];
  }

  public int size() {

    return this.Stack_Size + 1;
  }

  public int empty() {
    if (this.Stack_Size == -1) {
      return 1;
    }
    return 0;

  }

  public int top() {
    if (this.Stack_Size >= 0) {
      return this.Stack_arr[this.Stack_Size];
    }
    return -1;

  }
}

public class Main {


  public static void main(String[] args) throws IOException {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    int T = Integer.parseInt(br.readLine());
    Stack stack = new Stack(T);

    for (int i = 0; i < T; i++) {
      String S = br.readLine();

      if (S.equals("pop")) {
        bw.write(stack.pop() + "\n");
      } else if (S.equals("size")) {
        bw.write(stack.size() + "\n");
      } else if (S.equals("empty")) {
        bw.write(stack.empty() + "\n");
      } else if (S.equals("top")) {
        bw.write(stack.top() + "\n");
      } else {
        StringTokenizer st = new StringTokenizer(S);
        st.nextToken();
        stack.push(Integer.parseInt(st.nextToken()));
      }
    }
    bw.close();
  }
}