Geon
스택[BOJ] 본문
스택
import Foundation
struct Stack1 {
private var list: [Int] = []
mutating func push(_ value: Int) {
list.append(value)
}
mutating func pop() -> Int{
if list.isEmpty {
return -1
}
return list.removeLast()
}
func size() -> Int {
return list.count
}
func empty() -> Int {
return list.isEmpty ? 1 : 0
}
func top() -> Int {
return list.last ?? -1
}
}
var stack = Stack1()
for _ in 0..<Int(readLine()!)! {
let command = readLine()!.split(separator: " ")
switch command[0] {
case "push":
stack.push(Int(command[1])!)
case "pop":
print(stack.pop())
case "size":
print(stack.size())
case "empty":
print(stack.empty())
case "top":
print(stack.top())
default:
break
}
}
시간복잡도 O(n)
'코딩테스트' 카테고리의 다른 글
괄호[BOJ] (0) | 2022.03.22 |
---|---|
단어뒤집기[BOJ] (0) | 2022.03.22 |
신고 결과 받기 (0) | 2022.03.18 |
로또의 최고 순위와 최저 순위 (0) | 2022.03.16 |
신규 아이디 추천 (0) | 2022.03.15 |