#1 알고리즘
java.util 패키지의 Stack 클래스를 이용한다.
#2 코드
#2-2 자바
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
Stack<Integer> stack = new Stack<Integer>();
int commandCount = Integer.parseInt(br.readLine().trim());
for(int i = 0; i < commandCount; i++) {
String command = br.readLine().trim();
if(command.contains("push")) {
int pushValue = Integer.parseInt(command.substring(5)); // 6번째 문자부터 끝 문자까지 추출
stack.push(pushValue);
} else if(command.equals("pop")) {
if(stack.isEmpty()) {
bw.write("-1\n");
} else {
bw.write(Integer.toString(stack.pop()) + "\n");
}
} else if(command.equals("size")) {
if(stack.isEmpty()) {
bw.write("0\n");
} else {
bw.write(Integer.toString(stack.size()) + "\n");
}
} else if(command.equals("empty")) {
if(stack.isEmpty()) {
bw.write("1\n");
} else {
bw.write("0\n");
}
} else if(command.equals("top")) {
if(stack.isEmpty()) {
bw.write("-1\n");
} else {
bw.write(Integer.toString(stack.peek()) + "\n");
}
} else {
continue;
}
}
br.close();
bw.flush();
bw.close();
}
}
#2-2 코틀린
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.util.Stack
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
val stack = Stack<Int>()
val commandCount = br.readLine().trim().toInt()
for(i : Int in 1..commandCount) {
val command = br.readLine().trim()
if(command.contains("push")) {
val pushValue : Int = command.substring(5).toInt() // 6번째 문자부터 끝 문자까지 추출
stack.push(pushValue)
} else if(command == "pop") {
if(stack.isEmpty()) {
bw.write("-1\n")
} else {
bw.write("${stack.pop()}\n")
}
} else if(command == "size") {
if(stack.isEmpty()) {
bw.write("0\n")
} else {
bw.write("${stack.size}\n")
}
} else if(command == "empty") {
if(stack.isEmpty()) {
bw.write("1\n")
} else {
bw.write("0\n")
}
} else if(command == "top") {
if(stack.isEmpty()) {
bw.write("-1\n")
} else {
bw.write("${stack.peek()}\n")
}
} else {
continue
}
}
br.close()
bw.flush()
bw.close()
}
'문제 풀이 > 자료 구조' 카테고리의 다른 글
[백준] 1874 (스택 수열) (0) | 2024.01.06 |
---|---|
[백준] 1966 (프린터 큐) (0) | 2024.01.05 |
[백준] 9012 (괄호) (0) | 2023.12.30 |
[백준] 10845 (큐) (0) | 2023.12.14 |