You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何获取Stack栈结构的顶部两个元素?

实现方案

你要的查看栈顶两个元素的方法逻辑很简单:

  • 因为栈的内部数组是按入栈顺序存储的,array.last对应栈顶元素,array[array.count - 2]就对应次顶元素
  • 先判断数组元素数是否≥2,不满足的话直接返回nil,避免数组越界
  • 方法不需要修改栈内容,直接声明为普通只读方法即可,返回值用可选元组(Element, Element)?,分别对应「栈顶元素、次顶元素」

新增方法后的完整Stack代码

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 peekTopTwo() -> (top: Element, secondTop: Element)? {
    guard array.count >= 2 else {
      return nil
    }
    return (array[array.count - 1], array[array.count - 2])
  }
}

使用示例

var stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)

// 调用示例
if let topTwo = stack.peekTopTwo() {
    print("栈顶元素:\(topTwo.top),次顶元素:\(topTwo.secondTop)")
    // 输出:栈顶元素:3,次顶元素:2
} else {
    print("栈内元素不足2个")
}

内容的提问来源于stack exchange,提问作者Another

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 06:15:04