Junior — Middle
How do you implement a stack data structure in your system?
sobes.tech AI
Answer from AI
A stack is a data structure that operates on the Last In, First Out (LIFO) principle. In Swift, a stack can be implemented using an array, adding push and pop methods to manage elements.
Example of a stack implementation in Swift:
struct Stack<Element> {
private var elements: [Element] = []
mutating func push(_ element: Element) {
elements.append(element)
}
mutating func pop() -> Element? {
return elements.popLast()
}
func peek() -> Element? {
return elements.last
}
var isEmpty: Bool {
return elements.isEmpty
}
var count: Int {
return elements.count
}
}
// Usage:
var stack = Stack<Int>()
stack.push(10)
stack.push(20)
print(stack.pop() ?? "empty") // 20
print(stack.peek() ?? "empty") // 10
This stack can be used for storing action history, navigation, and other tasks where the order of element processing is important.