본문 바로가기
백준 문제풀이

백준 10828번 : 스택

by watergrace2u 2020. 9. 16.
반응형
SMALL

 

데이터 pop할 때 인덱스 값으로 --ptr을 넣어주어야한다는 점만 잘 기억하면 될 것 같다.

import java.util.Scanner;

public class Main {
	
	public static int[]stk = new int[100000];
	public static int ptr = 0; // 현재 스택에 쌓여있는 갯수
	
	
	private static void push(int x) {
		stk[ptr++]=x;
	}
	private static void pop() {
		if(ptr<=0)System.out.println(-1);
		else {
			System.out.println(stk[--ptr]);
		}
	}
	private static void size() {
		System.out.println(ptr);
	}
	private static void empty() {
		if(ptr<=0)System.out.println(1);
		else System.out.println(0);
	}
	private static void top() {
		if(ptr<=0)System.out.println(-1);
		else System.out.println(stk[ptr-1]);
	}
	
	public static void main(String[]args) {
		Scanner kb = new Scanner(System.in);
		int n = kb.nextInt();
		for(int i=0;i<n;i++) {
			String command = kb.next();
			if(command.equals("push")) {
				int x = kb.nextInt();
				push(x);
			}else if(command.equals("top")) top();
			else if(command.equals("pop"))pop();
			else if(command.equals("size"))size();
			else if(command.equals("empty"))empty();
		}
	}

}
반응형
LIST

댓글