[백준] 10828: 스택

강은서·2022년 2월 7일
0

백준

목록 보기
19/21
post-thumbnail

문제

문제 풀이

스택은 후입선출(Last In Frist Out)인 자료구조형이다.
자바에서 제공하고 있는 스택 클래스는 Vector클래스를 상속받고 있으며, 메소드는 Vetor클래스와 동일하다.

Vector클래스는 list인터페이스를 구현하였기 때문에 다음 문제는 ArrayList로 list를 생성하고 스택에서 사용되는 함수를 처리하는 프로그램을 작성하였다.

들어오는 입력값을 if문을 통하여서 다음 다섯가지 명령으로 처리하였다.

  • push
    - 후입선출이기 때문에 가장 마지막 인덱스 자리에 원소를 추가한다.
    - list.add(element)
  • pop
    - 가장 마지막 인덱스에 해당하는 정수를 출력하고, 삭제한다.
    - list.remove(index)
  • size
    - 리스트의 사이즈를 구하는 메소드를 통해서 구현한다.
  • empty
    - 리스트가 비어있는지 확인하는 메소드를 통해서 구현한다.
  • top
    - 리스트의 가장 마지막 인덱스에 해당하는 정수를 출력한다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        List<String> list = new ArrayList<String>();
        int index = 0;

        for(int i = 0 ; i < N; i++){
            StringTokenizer st = new StringTokenizer(br.readLine());
            String str = st.nextToken();
            if(str.equals("push")){
                list.add(st.nextToken());
                index++;
            }
            else if(str.equals("pop")){
                if(list.isEmpty()){
                    System.out.println("-1");
                }
                else{
                    System.out.println(list.get(index-1));
                    list.remove(index-1);
                    index--;
                }

            }
            else if(str.equals("size")){
                System.out.println(list.size());
            }
            else if(str.equals("empty")){
                if(list.isEmpty()){
                    System.out.println("1");
                }
                else{
                    System.out.println("0");
                }
            }
            else if(str.equals("top")){
                if(list.isEmpty()){
                    System.out.println("-1");
                }
                else{
                    System.out.println(list.get(index-1));
                }

            }
        }
    }
}

0개의 댓글