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())")