알고리즘
[백준] 10828번 스택 _ JAVA ( 주석 설명 ) 본문
풀이
1) 스택 Stack<Integer> stack = new Stack<>(); 을 만든다.
2) 각 명령마다 if 조건문을 만들어 처리를 해준다.
코드
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 {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine()); //명령의 수
Stack<Integer> stack = new Stack<>();
for(int i=0;i<N;++i){
st = new StringTokenizer(br.readLine());
String command = st.nextToken();
if(command.equals("pop")){ //pop 명령
if(stack.empty())
System.out.println(-1);
else
System.out.println(stack.pop());
}
else if(command.equals("size")){ //size 명령
System.out.println(stack.size());
}
else if(command.equals("empty")){ //empty 명령
if(stack.empty())
System.out.println(1);
else
System.out.println(0);
}
else if(command.equals("top")){ //top 명령
if(stack.empty())
System.out.println(-1);
else
System.out.println(stack.peek());
}
else{ //push 명령
int push_num = Integer.parseInt(st.nextToken());
stack.push(push_num);
}
}
}
}
'백준 - JAVA > 스택' 카테고리의 다른 글
[백준] 1874번 스택 수열 _ JAVA ( 주석 설명 ) (0) | 2023.03.17 |
---|---|
[백준] 4949번 균형잡힌 세상 _ JAVA ( 주석 설명 ) (0) | 2023.03.15 |
[백준] 9012번 괄호 _ JAVA ( 주석 설명 ) (0) | 2023.03.10 |
[백준] 10773번 제로 _ JAVA ( 주석 설명 ) (0) | 2023.03.10 |