<?php #输入一个栈的压栈序列和一个弹栈序列,判断该弹栈序列是否可能是压栈序列的输出 #例如压栈序列 12345,则弹栈序列可以是 54321 或者 45321 #解题思路,建一个空栈,按照压栈序列入栈,当压入的栈顶元素与弹栈序列的指针指向元素相同时,将元素弹出 #直到将压栈序列的元素全部压完,如果弹栈序列是正确的,则最后栈内元素可以按照弹栈序列顺序弹出,最后栈为空 #否则栈不为空 function test($push, $pop) { $len = count($push); $stack = array(); $i = 0; $j = 0; while ($i < $len) { array_push($stack, $push[$i]); $i++; echo "before: "; print_r($stack); while (!empty($stack) && $stack[count($stack) - 1] == $pop[$j]) { array_pop($stack); $j++; } echo "<br>after: "; print_r($stack); echo "<br>"; echo "<br>"; } return empty($stack); } $push = array(1, 2, 3, 4, 5); $pop = array(4, 5, 3, 1, 2); $t = test($push, $pop); var_dump($t); ?>
before: Array ( [0] => 1 )
after: Array ( [0] => 1 )
before: Array ( [0] => 1 [1] => 2 )
after: Array ( [0] => 1 [1] => 2 )
before: Array ( [0] => 1 [1] => 2 [2] => 3 )
after: Array ( [0] => 1 [1] => 2 [2] => 3 )
before: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
after: Array ( [0] => 1 [1] => 2 [2] => 3 )
before: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 )
after: Array ( [0] => 1 [1] => 2 )
bool(false)