본문으로 바로가기
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

백준알고리즘


https://www.acmicpc.net/problem/10828


백준알고리즘에서 Stack을 사용한 문제. 유의할 것은 스택에 값이 없는데 TOP 또는 POP을 했을 경우에 Exception이 발생하니, 조건을 태우면 된다.

import java.util.Scanner; import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int count = Integer.parseInt(scan.nextLine().trim()); int[] resultArray = new int[count]; Stack<Integer> stack = new Stack<Integer>(); int outValue = 0; for(int i=0; i < count; i++) { String str = scan.nextLine().trim(); if(str.contains("push")) { int data = Integer.parseInt(str.substring(5, str.length())); stack.push(data); } else if(str.contains("pop")) { if(stack.size() == 0) { resultArray[outValue] = -1; } else { resultArray[outValue] = stack.pop(); } outValue++; } else if(str.contains("size")) { resultArray[outValue] = stack.size(); outValue++; } else if(str.contains("empty")) { if(stack.size() == 0) { resultArray[outValue] = 1; } else { resultArray[outValue] = 0; } outValue++; } else if(str.contains("top")) { if(stack.size() == 0) { resultArray[outValue] = -1; outValue++; }else { resultArray[outValue] = stack.peek(); outValue++; } } } for(int i=0; i < outValue; i++) { System.out.println(resultArray[i]); } } }