01-10 13:07
Recent Posts
Recent Comments
관리 메뉴

miinsun

[BAEKJOON] λ°±μ€€ μŠ€νƒ/큐 10828 :: μŠ€νƒ JAVA λ³Έλ¬Έ

Algorithm/Baekjoon

[BAEKJOON] λ°±μ€€ μŠ€νƒ/큐 10828 :: μŠ€νƒ JAVA

miinsun 2022. 3. 14. 20:38

 

πŸ’¬  문제 μ„€λͺ…

μ •μˆ˜λ₯Ό μ €μž₯ν•˜λŠ” μŠ€νƒμ„ κ΅¬ν˜„ν•œ λ‹€μŒ, μž…λ ₯으둜 μ£Όμ–΄μ§€λŠ” λͺ…령을 μ²˜λ¦¬ν•˜λŠ” ν”„λ‘œκ·Έλž¨μ„ μž‘μ„±ν•˜μ‹œμ˜€.
λͺ…령은 총 λ‹€μ„― 가지이닀.

* push X: μ •μˆ˜ Xλ₯Ό μŠ€νƒμ— λ„£λŠ” 연산이닀.
* pop: μŠ€νƒμ—μ„œ κ°€μž₯ μœ„μ— μžˆλŠ” μ •μˆ˜λ₯Ό λΉΌκ³ , κ·Έ 수λ₯Ό 좜λ ₯ν•œλ‹€.
            λ§Œμ•½ μŠ€νƒμ— λ“€μ–΄μžˆλŠ” μ •μˆ˜κ°€ μ—†λŠ” κ²½μš°μ—λŠ” -1을 좜λ ₯ν•œλ‹€.size: μŠ€νƒμ— λ“€μ–΄μžˆλŠ” μ •μˆ˜μ˜ 개수λ₯Ό 좜λ ₯ν•œλ‹€.
* empty: μŠ€νƒμ΄ λΉ„μ–΄μžˆμœΌλ©΄ 1, μ•„λ‹ˆλ©΄ 0을 좜λ ₯ν•œλ‹€.
* top: μŠ€νƒμ˜ κ°€μž₯ μœ„μ— μžˆλŠ” μ •μˆ˜λ₯Ό 좜λ ₯ν•œλ‹€. λ§Œμ•½ μŠ€νƒμ— λ“€μ–΄μžˆλŠ” μ •μˆ˜κ°€ μ—†λŠ” κ²½μš°μ—λŠ” -1을 좜λ ₯ν•œλ‹€.

 

πŸ”¨  μž…μΆœλ ₯ 예

μž…λ ₯ 

  • 첫째 쀄에 μ£Όμ–΄μ§€λŠ” λͺ…λ Ήμ˜ 수 N (1 ≤ N ≤ 10,000)이 주어진닀.
  • λ‘˜μ§Έ 쀄뢀터 N개의 μ€„μ—λŠ” λͺ…령이 ν•˜λ‚˜μ”© 주어진닀.
  • μ£Όμ–΄μ§€λŠ” μ •μˆ˜λŠ” 1보닀 ν¬κ±°λ‚˜ κ°™κ³ , 100,000보닀 μž‘κ±°λ‚˜ κ°™λ‹€.
  • λ¬Έμ œμ— λ‚˜μ™€μžˆμ§€ μ•Šμ€ λͺ…령이 μ£Όμ–΄μ§€λŠ” κ²½μš°λŠ” μ—†λ‹€.

 

좜λ ₯

  • 좜λ ₯ν•΄μ•Όν•˜λŠ” λͺ…령이 μ£Όμ–΄μ§ˆ λ•Œλ§ˆλ‹€, ν•œ 쀄에 ν•˜λ‚˜μ”© 좜λ ₯ν•œλ‹€.

 

예제 μž…λ ₯ 1)

14
push 1
push 2
top
size
empty
pop
pop
pop
size
empty
pop
push 3
empty
top

 

예제 좜λ ₯ 1)

2
2
0
2
1
-1
0
1
-1
0
3

 

예제 μž…λ ₯ 2)

7
pop
top
push 123
top
pop
top
pop

 

예제 좜λ ₯ 2)

-1
-1
123
123
-1
-1

​

 

​

πŸ’»  Main.java

  • μŠ€νƒμ„ λ‹€λ£¨λŠ” κ°€μž₯ κΈ°λ³Έ 문제
  • μŠ€νƒμ˜ ν•¨μˆ˜λ“€ push, pop, peek, add, isEmpty 
  • Scannerλ₯Ό μ΄μš©ν•˜λ©΄ μ‹œκ°„ μ΄ˆκ³Όκ°€ 뜨기 λ•Œλ¬Έμ— BufferedReaderλ₯Ό μ‚¬μš©ν•΄ μ •μˆ˜ μž…λ ₯을 ν•œλ‹€
/* λ°±μ€€ μŠ€νƒ/큐 - 10828 :: μŠ€νƒ */
import java.util.*;
import java.io.*;

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		
		
		Stack<Integer> stack = new Stack<>();
		for(int i = 0; i < n; i++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			String s = st.nextToken();
			switch(s){
				case "push" : 
					stack.push(Integer.parseInt(st.nextToken()));
					break;
				case "pop" :{
					if(stack.isEmpty()) System.out.println(-1);
					else System.out.println(stack.pop());
					break;
				}
				case "size" : 
					System.out.println(stack.size());
					break;
				case "empty" :{
					if(stack.isEmpty()) System.out.println(1);
					else System.out.println(0);
					break;
				}
				case "top" : {
					if(stack.isEmpty()) System.out.println(-1);
					else System.out.println(stack.peek());
					break;
				}
			}
		}
		
	}
}
Comments