Created
April 21, 2017 06:59
-
-
Save geoseong/e4a6a514b83d03f2f38aa7a8ec763325 to your computer and use it in GitHub Desktop.
BaekJoon Algorithm Study : 10828_Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
# 문제 | |
push X: 정수 X를 스택에 넣는 연산이다. | |
pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다. | |
size: 스택에 들어있는 정수의 개수를 출력한다. | |
empty: 스택이 비어있으면 1, 아니면 0을 출력한다. | |
top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다. | |
# 입력 | |
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. | |
둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. | |
주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다. | |
ex) | |
14 | |
push 1 | |
push 2 | |
top | |
size | |
empty | |
pop | |
pop | |
pop | |
size | |
empty | |
pop | |
push 3 | |
empty | |
top | |
# 출력 | |
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다. | |
ex) | |
2 | |
2 | |
0 | |
2 | |
1 | |
-1 | |
0 | |
1 | |
-1 | |
0 | |
3 | |
*/ | |
package baekjoon.Stack_10828; | |
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{ | |
new Main(); | |
} | |
Main() throws IOException{ | |
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | |
Stack<Integer> stack = new Stack<>(); | |
StringBuilder sb = new StringBuilder(); | |
// line 1. | |
StringTokenizer token = new StringTokenizer(br.readLine(), " "); | |
int testcase = Integer.parseInt(token.nextToken()); | |
while(testcase-- > 0){ | |
// line n. | |
token = new StringTokenizer(br.readLine(), " "); | |
String word = token.nextToken(); | |
String nextline = "\n"; | |
if(word.equals("push")){ | |
int element = Integer.parseInt(token.nextToken()); | |
stack.push(element); | |
}else if(word.equals("pop")){ | |
if(stack.size()==0){ | |
sb.append("-1"+nextline); | |
} | |
else{ | |
sb.append(stack.pop()+nextline); | |
} | |
}else if(word.equals("size")){ | |
sb.append(stack.size()+nextline); | |
}else if(word.equals("empty")){ | |
if(stack.size()==0) sb.append("1"+nextline); | |
else sb.append("0"+nextline); | |
}else{ // "top" | |
if(stack.size()==0) sb.append("-1"+nextline); | |
else sb.append(stack.peek()+nextline); | |
} | |
} //end while | |
System.out.println(sb.toString()); | |
} // end Main() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment