문제
풀이코드
// [BOJ] 10828 - 스택
public struct Stack<T> {
private var elements = [T]()
public init() {}
public mutating func pop() -> T? {
return self.elements.popLast()
}
public mutating func push(_ element: T) {
self.elements.append(element)
}
public func top() -> T? {
return self.elements.last
}
public var empty: Int {
return self.elements.isEmpty ? 1 : 0
}
public var size: Int {
return self.elements.count
}
}
let N = Int(readLine()!)!
var intStack = Stack<Int>()
var lastElement : Int?
for _ in 0..<N {
let command = readLine()!.split(separator: " ")
switch command[0] {
case "push":
intStack.push(Int(command[1])!)
case "pop":
lastElement = intStack.pop()
print(lastElement == nil ? -1 : lastElement!)
case "size":
print(intStack.size)
case "empty":
print(intStack.empty)
default:
lastElement = intStack.top()
print(lastElement == nil ? -1 : lastElement!)
}
}
풀이과정
https://ai-hong.tistory.com/198?category=1001478
에서 설명한 것과 같이 오늘은 스택을 이용한 문제를 풀었다.
개념을 공부하고 문제를 보니 큰 어려움은 없었다.
구조체로 스택을 선언하고, 다만 문제에 나와있는대로 그 내용을 조금 변경했다.
문제에
- push X: 정수 X를 스택에 넣는 연산이다.
- pop: 스택에서 가장 위에 있는 정수를 빼고, 그 수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
- size: 스택에 들어있는 정수의 개수를 출력한다.
- empty: 스택이 비어있으면 1, 아니면 0을 출력한다.
- top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.
가 나와 있기 때문에 이를 따라 구조체를 선언해 주었고,
Switch - case 구문을 통하여 각각의 상황에 맞는 함수 혹은 파라미터를 호출해 주었다 :)
문제에서 지정된 명령어 이외의 명령은 없다고 나와있기에
"top"같은 경우, default 에 기능을 넣어 주었다
깔끔히 통과!