Powershell 最大值堆栈实现
下面代碼基于一個算法題目來實現(xiàn)一個用線性時間得到堆棧最大值的代碼。
?
cls
$maxStackConut =5
$stackTopIndex =-1
$stack = New-Object int[] ($maxStackConut)
$link2NextMaxItem = New-Object int[] ($maxStackConut)
$maxStackItemIndex=-1
function Push([int] $Value)
{
?? if($stackTopIndex -eq ($maxStackConut-1))
?? {
???? throw "Stack is full"
?? }
?? else
?? {
????? $script:stackTopIndex++
????? $script:stack[$stackTopIndex] = $Value
?? if($Value -ge (Max))
?? {
????? $script:link2NextMaxItem[$stackTopIndex] = $maxStackItemIndex
?? $script:maxStackItemIndex = $stackTopIndex
?? }
?? else
?? {
???? $script:link2NextMaxItem[$stackTopIndex] = -1
?? }
?? }
?? "Push:$Value stack = $stack link2NextMaxItem=$link2NextMaxItem maxValue = $(Max)"
??
}
function Pop
{
?? if($stackTopIndex -eq -1)
?? {
???? throw "Stack is empty"
?? }
?? else
?? {
????? $returnValue =$stack[$stackTopIndex]
????? $script:stack[$stackTopIndex] = 0
?? if($stackTopIndex -eq $maxStackItemIndex)
?? {
?? $script:maxStackItemIndex = $link2NextMaxItem[$stackTopIndex]
?? }
?? $script:stackTopIndex--
?? }
?? "Pop:$returnValue stack = $stack link2NextMaxItem=$link2NextMaxItem maxValue = $(Max)"
}
function Max
{
? if($maxQueueItemIndex -ge 0)
? {
??? return $stack[$maxStackItemIndex]
? }
? else
? {
??? return -10
? }
}
?
運行西面的測試代碼:
Push 1
Push 2
Push 5
Push 4
Push 6
Pop
Pop
Pop
Pop
Pop
Push 3
結(jié)果
Push:1 stack = 1 0 0 0 0 link2NextMaxItem=-1 0 0 0 0 maxValue = -10
Push:2 stack = 1 2 0 0 0 link2NextMaxItem=-1 0 0 0 0 maxValue = -10
Push:5 stack = 1 2 5 0 0 link2NextMaxItem=-1 0 1 0 0 maxValue = -10
Push:4 stack = 1 2 5 4 0 link2NextMaxItem=-1 0 1 2 0 maxValue = -10
Push:6 stack = 1 2 5 4 6 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Pop:6 stack = 1 2 5 4 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Pop:4 stack = 1 2 5 0 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Pop:5 stack = 1 2 0 0 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Pop:2 stack = 1 0 0 0 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Pop:1 stack = 0 0 0 0 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
Push:3 stack = 3 0 0 0 0 link2NextMaxItem=-1 0 1 2 3 maxValue = -10
?
我們可以看到整個的執(zhí)行過程
?
?
posted on 2010-12-16 16:02 沙漠魚 閱讀(...) 評論(...) 編輯 收藏轉(zhuǎn)載于:https://www.cnblogs.com/zhaojun20002003/archive/2010/12/16/1908313.html
總結(jié)
以上是生活随笔為你收集整理的Powershell 最大值堆栈实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux配置 DNS and BIND
- 下一篇: 表格闪退怎么解决_win10中excel