728x90
문제 : https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
입력을 받을 때 Scanner 보다 BufferedReader를 사용하여 더 빠른 처리가 가능하게 하였다.
System.out 을 이용하여 출력 할 때에는 [ 조건식 ? true : false ] 를 이용하여, 간단하게 코드를 구성하였다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
Stack<Integer> stack = new Stack<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
for (int i=0;i<N;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
String s= st.nextToken();
if (s.equals("push")){
int a= Integer.parseInt(st.nextToken());
stack.push(a);
}
else if (s.equals("pop")){
System.out.println(stack.isEmpty() ? -1 : stack.pop());
}
else if (s.equals("size")){
System.out.println(stack.size());
}
else if (s.equals("empty")){
System.out.println(stack.isEmpty() ? 1 : 0);
}
else if (s.equals("top")){
System.out.println(stack.isEmpty() ? -1 : stack.peek());
}
}
}
}
728x90