栈 Stack<T>(LIFO)

数组和集合

#bash 没有栈:用数组实现,push 添加到末尾,pop 从末尾取出
intStack=()
intStack+=(1)
intStack+=(3)
intStack+=(5)

#索引 -1 是最后一个元素(bash 4.2 及更高版本)
top=${intStack[-1]}
#top is 5

#pop:读取最后一个元素,再将其删除;
#加引号是为了避免 [-1] 被当作文件名模式
first=${intStack[-1]}
unset 'intStack[-1]'
#first is 5
second=${intStack[-1]}
unset 'intStack[-1]'
#second is 3
third=${intStack[-1]}
unset 'intStack[-1]'
#third is 1

#pop 函数不能写成 $(pop) 调用:$( ) 在子 shell 中运行它,
#而那里的栈只是副本

((${#intStack[@]} == 0)) && isEmpty=true || isEmpty=false
#isEmpty is true

echo "top is $top"
echo "first is $first"
echo "second is $second"
echo "third is $third"
echo "isEmpty is $isEmpty"