10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
문제제목 : 스택
문제난이도 : 실버4
문제 유형 : 스택
문제
정수를 저장하는 스택을 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 다섯 가지이다.
- push X: 정수 X를 스택에 넣는 연산이다.
- pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 스택에 들어있는 정수의 개수를 출력한다.
- empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
- top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
입력
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class B10828 {
static ArrayList<Integer> stack = new ArrayList<>();
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int count = Integer.parseInt(br.readLine());
Stack stack = new Stack();
ArrayList<Integer> output = new ArrayList<>();
for (int i = 0; i < count; i++) {
String input = br.readLine();
if (input.contains("push")) {
int key = Integer.parseInt(input.split(" ")[1]);
stack.push(key);
} else if (input.equals("pop")) {
output.add(stack.pop());
} else if (input.equals("size")) {
output.add(stack.size());
} else if (input.equals("top")) {
output.add(stack.top());
} else if (input.equals("empty")) {
output.add(stack.empty());
}
}
for (Integer str : output) {
System.out.println(str);
}
}
}
class Stack {
ArrayList<Integer> stack;
public Stack() {
stack = new ArrayList<Integer>();
}
public void push(int data) {
stack.add(data);
}
public int pop() {
int index = stack.size() - 1;
if (stack.size() == 0) {
return -1;
} else {
int num = stack.get(index);
stack.remove(index);
return num;
}
}
public int size() {
return stack.size();
}
public int empty() {
if (stack.size() == 0)
return 1;
else
return 0;
}
public int top() {
if (size() == 0)
return -1;
else
return stack.get(size() - 1);
}
}
아이디어
자료구조에서 배운 스택을 구현한다.
추가 학습
1. Stack
import java.util.Stack;
public class StackCode {
public static void main(String[] args) {
Stack<Integer> intstack = new Stack<>();
System.out.println("[스택] : " + intstack.toString());
System.out.println("비어있나? : " + intstack.isEmpty());
intstack.push(1);
intstack.push(2);
intstack.push(3);
intstack.push(4);
System.out.println("[스택] : " + intstack.toString());
System.out.println("pop : " + intstack.pop());
System.out.println("[스택] : " + intstack.toString());
System.out.println("peek : " + intstack.peek());
System.out.println("size : " + intstack.size());
}
}
2. [ push 3 ] 을 문자열 배열로 바꾸기.
- String[] input = br.readLine().split(" ");
'코딩테스트 준비 > JAVA 코테' 카테고리의 다른 글
백준 11279. 최대힙 (힙, 우선순위큐) (0) | 2021.02.25 |
---|---|
JAVA 입력 input 관련 (0) | 2021.02.25 |
백준 5639. 이진 검색 트리 (0) | 2021.02.24 |
백준 1991. 트리 순회 (0) | 2021.02.24 |
백준 1966. 프린터 큐 (0) | 2021.02.23 |
댓글