This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
/**
*File:array_stack.swift
*CreatedTime:2023-01-09
*Author:nuomi1(nuomi1@qq.com)
*/
/*基於陣列實現的堆疊*/
classArrayStack{
privatevarstack:[Int]
init(){
//初始化串列(動態陣列)
stack=[]
}
/*獲取堆疊的長度*/
funcsize()->Int{
stack.count
}
/*判斷堆疊是否為空*/
funcisEmpty()->Bool{
stack.isEmpty
}
/*入堆疊*/
funcpush(num:Int){
stack.append(num)
}
/*出堆疊*/
@discardableResult
funcpop()->Int{
ifisEmpty(){
fatalError("堆疊為空")
}
returnstack.removeLast()
}
/*訪問堆疊頂元素*/
funcpeek()->Int{
ifisEmpty(){
fatalError("堆疊為空")
}
returnstack.last!
}
/*將List轉化為Array並返回*/
functoArray()->[Int]{
stack
}
}
@main
enum_ArrayStack{
/*DriverCode*/
staticfuncmain(){
/*初始化堆疊*/
letstack=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())")
/*訪問堆疊頂元素*/
letpeek=stack.peek()
print("堆疊頂元素 peek = \(peek)")
/*元素出堆疊*/
letpop=stack.pop()
print("出堆疊元素 pop = \(pop),出堆疊後 stack = \(stack.toArray())")