hello-algo/zh-hant/codes/swift/chapter_stack_and_queue/array_stack.swift

86 lines
1.8 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: array_stack.swift
* Created Time: 2023-01-09
* Author: nuomi1 (nuomi1@qq.com)
*/
/* */
class ArrayStack {
private var stack: [Int]
init() {
//
stack = []
}
/* */
func size() -> Int {
stack.count
}
/* */
func isEmpty() -> Bool {
stack.isEmpty
}
/* */
func push(num: Int) {
stack.append(num)
}
/* */
@discardableResult
func pop() -> Int {
if isEmpty() {
fatalError("堆疊為空")
}
return stack.removeLast()
}
/* */
func peek() -> Int {
if isEmpty() {
fatalError("堆疊為空")
}
return stack.last!
}
/* List Array */
func toArray() -> [Int] {
stack
}
}
@main
enum _ArrayStack {
/* Driver Code */
static func main() {
/* */
let stack = ArrayStack()
/* */
stack.push(num: 1)
stack.push(num: 3)
stack.push(num: 2)
stack.push(num: 5)
stack.push(num: 4)
print("堆疊 stack = \(stack.toArray())")
/* */
let peek = stack.peek()
print("堆疊頂元素 peek = \(peek)")
/* */
let pop = stack.pop()
print("出堆疊元素 pop = \(pop),出堆疊後 stack = \(stack.toArray())")
/* */
let size = stack.size()
print("堆疊的長度 size = \(size)")
/* */
let isEmpty = stack.isEmpty()
print("堆疊是否為空 = \(isEmpty)")
}
}