Junior — Middle
Kuidas te oma süsteemis virna andmestruktuuri rakendate?
sobes.tech AI
Vastus AI-lt
Stack is a data structure that operates on the LIFO (Last In, First Out) principle. In Swift, you can implement a stack using an array, adding push and pop methods to manage the elements.
Example of implementing a stack 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
Such a stack can be used to store action history, navigation, and other tasks where the order of processing elements is important.