下面代码基于一个算法题目来实现一个用线性时间得到堆栈最大值的代码。
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
结果
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
我们可以看到整个的执行过程