문제에서 제시하는 명령어를 기반으로 스택을 구현한 다음 각각의 명령어를 입력했을때 출력 결과가 나와야한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static int N;
static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
String op = st.nextToken();
Integer value = -1;
if (st.countTokens() == 1) {
value = Integer.valueOf(st.nextToken());
}
print(op, value);
}
}
public static void print(String op, Integer value) {
switch (op) {
case "push":
stack.push(value);
break;
case "pop":
if (stack.empty())
System.out.println(-1);
else
System.out.println(stack.pop());
break;
case "top":
if (stack.empty())
System.out.println(-1);
else
System.out.println(stack.peek());
break;
case "size":
System.out.println(stack.size());
break;
case "empty":
if (stack.empty())
System.out.println(1);
else
System.out.println(0);
break;
default:
break;
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Stack stack = new Stack();
N = Integer.parseInt(st.nextToken());
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
String op;
int value = 0;
op = st.nextToken();
if (st.countTokens() == 1) {
value = Integer.parseInt(st.nextToken());
}
if (op.equals("push"))
stack.push(value);
else if (op.equals("pop"))
stack.pop();
else if (op.equals("size"))
stack.size();
else if (op.equals("empty"))
stack.empty();
else
stack.top();
}
}
public static class Stack {
private ArrayList<Integer> stack;
private int index;
public Stack() {
this.stack = new ArrayList<>();
this.index = 0;
}
public void push(int value) {
this.stack.add(value);
this.index++;
}
public void pop() {
if (this.stack.size() <= 0)
System.out.println(-1);
else {
System.out.println(this.stack.get(this.index - 1));
this.stack.remove(this.index - 1);
this.index--;
}
}
public void top() {
if (this.stack.size() <= 0)
System.out.println(-1);
else
System.out.println(this.stack.get(this.index - 1));
}
public void size() {
System.out.println(this.stack.size());
}
public void empty() {
if (this.index <= 0)
System.out.println(1);
else
System.out.println(0);
}
}
}