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
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?