How do I implement a deque in Swift?

A deque (double-ended queue) is a data structure that allows the addition and removal of elements from both ends. In Swift, we can efficiently implement a deque using an array or a linked list. Below is an example of how to create a simple deque using Swift's built-in array functionality.

struct Deque { private var elements: [T] = [] var isEmpty: Bool { return elements.isEmpty } var count: Int { return elements.count } mutating func appendFront(_ element: T) { elements.insert(element, at: 0) } mutating func appendBack(_ element: T) { elements.append(element) } mutating func removeFront() -> T? { return isEmpty ? nil : elements.removeFirst() } mutating func removeBack() -> T? { return isEmpty ? nil : elements.removeLast() } func peekFront() -> T? { return elements.first } func peekBack() -> T? { return elements.last } } // Example usage: var deque = Deque() deque.appendBack(1) deque.appendBack(2) deque.appendFront(0) print(deque.removeFront()!) // Output: 0 print(deque.removeBack()!) // Output: 2 print(deque.isEmpty) // Output: false print(deque.count) // Output: 1

deque Swift data structure double-ended queue implementation