알고리즘문풀 with SWIFT/Baekjoon

swift ) 백준 10866 - 덱

유사앱등이 2023. 3. 17. 01:56

 

덱 구현하여 풀이.. 

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
	}
}

 

스택큐 활용해서(?) 덱 구현..