feat: add Swift codes for stack article

This commit is contained in:
nuomi1
2023-01-09 23:02:22 +08:00
parent a86bdeb7cd
commit 47f017177b
5 changed files with 338 additions and 0 deletions

View File

@ -0,0 +1,84 @@
/**
* 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)
}
/* */
func pop() -> Int {
if stack.isEmpty {
fatalError("栈为空")
}
return stack.removeLast()
}
/* 访 */
func peek() -> Int {
if stack.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)")
}
}