덱 구현하여 풀이..
struct Deque {
var leftStack: [Int]
var rightStack: [Int] = []
init(_ leftStack: [Int]) {
self.leftStack = leftStack
}
var count: Int {
return leftStack.count + rightStack.count
}
func isEmpty() -> Bool {
return leftStack.isEmpty && rightStack.isEmpty
}
mutating func pushFirst(_ element: Int) {
rightStack.append(element)
}
mutating func pushLast(_ element: Int) {
leftStack.append(element)
}
mutating func popFirst() -> Int {
if rightStack.isEmpty {
rightStack = leftStack.reversed()
leftStack.removeAll()
}
return rightStack.popLast() ?? -1
}
mutating func popLast() -> Int {
var returnValue: Int
if leftStack.isEmpty {
rightStack.reverse()
returnValue = rightStack.popLast() ?? -1
rightStack.reverse()
} else {
returnValue = leftStack.popLast() ?? -1
}
return returnValue
}
}
let caseNum = Int(readLine()!)!
var deque = Deque([])
for _ in 1...caseNum {
let input = readLine()!.split(separator: " ").map{String($0)}
switch input[0] {
case "push_front":
deque.pushFirst(Int(input[1])!)
case "push_back":
deque.pushLast(Int(input[1])!)
case "pop_front":
print(deque.popFirst())
case "pop_back":
print(deque.popLast())
case "size":
print(deque.count)
case "empty":
deque.isEmpty() ? print("1") : print("0")
case "front":
if deque.isEmpty() {
print("-1")
} else {
print(deque.rightStack.last ?? deque.leftStack[0])
}
case "back":
if deque.isEmpty() {
print("-1")
} else {
print(deque.leftStack.last ?? deque.rightStack[0])
}
default:
break
}
}
스택큐 활용해서(?) 덱 구현..
'알고리즘문풀 with SWIFT > Baekjoon' 카테고리의 다른 글
swift ) 백준 2164 - 카드2 (0) | 2023.03.17 |
---|---|
swift ) 백준 1966 - 프린터 큐 (0) | 2022.07.01 |
swift ) 백준 1924 - 2007 (0) | 2022.06.29 |
swift ) 백준 14002 - 가장 긴 증가하는 부분 수열 4 (0) | 2022.06.26 |
swift ) 백준 9251 - LCS (0) | 2022.06.25 |