如何在Swift中获取堆栈的前两个元素



我从raywendrlich网站上获得了这个堆栈实现,但我想实现一个窥探堆栈前两个元素的方法。当然,接收它的值

struct Stack<Element> {
fileprivate var array: [Element] = []

mutating func push(_ element: Element) {
array.append(element)
}

mutating func pop() -> Element? {
return array.popLast()
}

func peek() -> Element? {
return array.last
}
}

我该怎么做?谢谢

import UIKit
struct Stack<Element> {
fileprivate var array: [Element] = []

mutating func push(_ element: Element) {
array.append(element)
}

mutating func pop() -> Element? {
return array.popLast()
}

func peek() -> Element? {
return array.last
}

func peekTwoElements() -> [Element]? {
let length = array.count
return (length >= 2 ? [array[length-1], array[length-2]] : nil)
}
}

最新更新