반응형
SMALL
데이터 pop할 때 인덱스 값으로 --ptr을 넣어주어야한다는 점만 잘 기억하면 될 것 같다.
import java.util.Scanner;
public class Main {
public static int[]stk = new int[100000];
public static int ptr = 0; // 현재 스택에 쌓여있는 갯수
private static void push(int x) {
stk[ptr++]=x;
}
private static void pop() {
if(ptr<=0)System.out.println(-1);
else {
System.out.println(stk[--ptr]);
}
}
private static void size() {
System.out.println(ptr);
}
private static void empty() {
if(ptr<=0)System.out.println(1);
else System.out.println(0);
}
private static void top() {
if(ptr<=0)System.out.println(-1);
else System.out.println(stk[ptr-1]);
}
public static void main(String[]args) {
Scanner kb = new Scanner(System.in);
int n = kb.nextInt();
for(int i=0;i<n;i++) {
String command = kb.next();
if(command.equals("push")) {
int x = kb.nextInt();
push(x);
}else if(command.equals("top")) top();
else if(command.equals("pop"))pop();
else if(command.equals("size"))size();
else if(command.equals("empty"))empty();
}
}
}
반응형
LIST
'백준 문제풀이' 카테고리의 다른 글
백준 2751번 : 수 정렬하기2 - 시간초과 문제해결 - Collections.sort() 사용하기 (0) | 2023.06.29 |
---|---|
[python] 백준 1924: 2007년 (0) | 2021.06.05 |
[python] 백준 1157번: 단어공부 (0) | 2021.05.14 |
백준 1065번 : 한수 (0) | 2020.09.24 |
백준 4673번 : 셀프넘버 (0) | 2020.09.24 |
댓글