예제 입력1:
14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top
예제 출력1:
2
2
0
2
1
-1
0
1
-1
0
3
예제 입력2:
7
pop
top
push 123
top
pop
top
pop
예제 출력2:
-1
-1
123
123
-1
-1
StringBuffer sb = new StringBuffer();
sb.append(-1+"\n");
코드1 (System.out.Println 사용)
import java.util.*;
public class No_10828 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Stack <Integer> stack=new Stack<Integer>();
int cnt=sc.nextInt();
for(int i=0;i<cnt;i++) {
String str=sc.next();
if(str.contains("push")) {
int num=sc.nextInt();
stack.push(num);
}else if(str.equals("pop")) {
if(!stack.isEmpty()) {
System.out.println(stack.pop());
}
else {
System.out.println(-1);
}
}
else if(str.equals("size")) {
System.out.println(stack.size());
}
else if(str.equals("empty")) {
if(!stack.isEmpty()) {
System.out.println(0);
}
else
System.out.println(1);
}
else if(str.equals("top")) {
if(!stack.isEmpty())
System.out.println(stack.peek());
else
System.out.println(-1);
}
}
}
}
코드 1: 실행 결과
import java.util.*;
public class No_10828 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
StringBuffer sb = new StringBuffer();
Stack <Integer> stack=new Stack<Integer>();
int cnt=sc.nextInt();
for(int i=0;i<cnt;i++) {
String str=sc.next();
if(str.contains("push")) {
int num=sc.nextInt();
stack.push(num);
}else if(str.equals("pop")) {
if(!stack.isEmpty()) {
sb.append(stack.pop()+"\n");
}
else {
sb.append(-1+"\n");
}
}
else if(str.equals("size")) {
sb.append(stack.size()+"\n");
}
else if(str.equals("empty")) {
if(!stack.isEmpty()) {
sb.append(0+"\n");
}
else
sb.append(1+"\n");
}
else if(str.equals("top")) {
if(!stack.isEmpty())
sb.append(stack.peek()+"\n");
else
sb.append(-1+"\n");
}
}
System.out.println(sb);
}
}
코드 2: 실행 결과