반응형
문제
https://www.acmicpc.net/problem/28278
28278번: 스택 2
첫째 줄에 명령의 수 N이 주어진다. (1 ≤ N ≤ 1,000,000) 둘째 줄부터 N개 줄에 명령이 하나씩 주어진다. 출력을 요구하는 명령은 하나 이상 주어진다.
www.acmicpc.net
풀이
스택 자료구조의 동작과정을 안다면 쉽게 풀 수 있는 문제
스택을 struct나 class로 구현해도 문제없지만,
간단하게 구현이 가능해서 따로 구현하지는 않았습니다.
소스코드
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
let n = Int(readLine()!)! | |
var stack: [Int] = [] | |
for _ in 0..<n { | |
let input = readLine()!.split(separator: " ").map { Int($0)! } | |
let command = input.first! | |
switch command { | |
case 1: | |
let x = input.last! | |
stack.append(x) | |
case 2: | |
print(stack.popLast() ?? -1) | |
case 3: | |
print(stack.count) | |
case 4: | |
print(stack.isEmpty ? 1: 0) | |
case 5: | |
print(stack.last ?? -1) | |
default: fatalError() | |
} | |
} |
후기
스택을 처음 접할 때, 연습삼아서 풀기에는 좋을 것 같다.
완전 생 기본문제
반응형
'PS > 백준' 카테고리의 다른 글
[BOJ] 백준 10799 쇠막대기 (Swift) (1) | 2023.11.19 |
---|---|
[BOJ] 백준 1935 후위 표기식2 (Swift) (1) | 2023.11.19 |
[BOJ] 백준 1205 등수 구하기 (Swift) (0) | 2023.06.14 |
[BOJ] 백준 6080 Bad Grass (Swift) (1) | 2023.06.09 |
[BOJ] 백준 1543 문서 검색 (Swift) (0) | 2023.06.02 |