栈——PowerShell版

时间:2021-09-30 15:32:39

上一篇讲过队列(queue),队列就像是居民楼里的垃圾管道,从楼道的垃圾管道的入口处将垃圾扔进去,清洁工会从一楼垃圾管道的出口处将垃圾拿走。每一层的垃圾通道入口与一楼的垃圾管道出口之间都形成了一个队列,先被扔进垃圾道里的垃圾会先到达垃圾通道的出口,即:先进先出。

栈是一种更简单的数据结构,如果队列是垃圾通道,那栈就是垃圾桶,先扔进垃圾桶的垃圾都被压桶底了,反而是后仍进去的垃圾会先被倒出来。这种后进先出的数据结构,就是——栈(stack)。

队列的三要素是队伍,队头,队尾。

在PowerShell中可以用一个动态数组表示队伍,用两个变量来表示队头和队尾之于数组中的位置。

队列(垃圾道)有两头,数据从一头进,另一头出。进的那头叫队尾,出的那头叫队头。

栈(垃圾桶)只有一头,从哪头进就从哪头出,进的那头叫顶(垃圾桶都是立着放)。

在PowerShell中可以用一个动态数组来表示栈,栈顶之于数组的位置就用一个变量来记录。

$stack = New-Object System.Collections.ArrayList
#Create a stack of numbers.
$flag = $true
while($flag)
{
$input = Read-Host "Put a number into the stack"
$stack.Add([int] $input)
$choice = Read-Host "Press 'c' to continue, any other key to quit"
if($choice -ne 'c')
{
$flag = $false
}
}
$top = $stack.count-1
$stack_top = $stack[$top]
#Show the top number of this stack.
Write-Host "The top of the stack is:" -ForegroundColor green
Write-Host $stack_top -ForegroundColor green

以上这段代码简述了栈的创建和栈顶元素的查看方法。
现在来举个现实世界中的例子,你立刻就会明白什么是栈——发扑克牌。

栈——PowerShell版

首先创建一套扑克牌:

#Create a set of pokers.
$pokers = New-Object System.Collections.ArrayList
$pokerModel = @{"pokers"="2,3,4,5,6,7,8,9,10,J,Q,K,A,SmallKing,BigKing";"colors"="spade,heart,club,diamond"}
$pokerEles = $pokerModel.Item("pokers").Split(",")
$pokerColors = $pokerModel.Item("colors").Split(",")
foreach($pokerEle in $pokerEles)
{
if(($pokerEle -eq "SmallKing") -or ($pokerEle -eq "BigKing"))
{
$pokers.Add($pokerEle)
}
else
{
foreach($color in $pokerColors)
{
$newPoker = $color + "_" + $pokerEle
$pokers.Add($newPoker)
}
}
}

然后对这幅扑克进行洗牌(将第一张牌随机放入整副牌中,重复10000次):

#Shuffle.
for($i=0;$i -le 10000;$i++)
{
$randomPlace = Get-Random -min 0 -max $pokers.count
$selectedPoker = $pokers[0]
$pokers.RemoveAt(0)
$pokers.Insert($randomPlace, $selectedPoker)
}

然后我们把洗好的牌放进“栈”中(发牌器就是栈),像下图这个样子。然后开始发牌(每次发牌都是从栈顶pop出一张)——

栈——PowerShell版

#Push the cards into the stack.
$myStack = new-object System.Collections.Stack
foreach($poker in $pokers)
{
$myStack.Push($poker)
}
#Start the deal.
Write-Host "---Start dealing---" -ForegroundColor green
$flag = $true
while($flag)
{
$myStack.Pop()
$choice = Read-Host "Press 'c' to continue, any other key to quit"
if($choice -ne 'c')
{
$flag = $false
}
else
{
Write-Host "---Continue dealing---" -ForegroundColor yellow
}
}

运行结果如下:
栈——PowerShell版

到此,一个发纸牌的过程就完成了,而这个发牌器就是栈,装牌的过程就是入栈的过程,发牌的过程就是出栈的过程。