This article mainly introduces the PHP implementation of the stack and pop-up sequence, has a certain reference value, now share to everyone, the need for friends can refer to
Title Description
Enter a sequence of two integers, and the first sequence represents the stacking order of the stack, judging whether the second sequence is the pop-up order for the stack. Assume that all the numbers that are pressed into the stack are not equal. For example 1,2,3,4,5
, a sequence is the indentation order of a stack, and the sequence 4,5,3,2,1
is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2
it cannot be the pop-up sequence of the stack sequence. (Note: The lengths of the two sequences are equal)
Time limit: 1 seconds space limit: 32768K
<?phpfunction Ispoporder ($pushValue, $popValue) { $stack = new Splstack; $count = count ($pushValue); for ($i = 0, $j = 0; $i < $count; $i + +) { $stack->push ($pushValue [$i]); while (! $stack->isempty () && $stack->top () = = $popValue [$j] && $j < $count) { $stack Pop (); $j + +; } } return $stack->isempty ();} Var_dump (Ispoporder ([1, 2, 3, 4, 5], [4, 5, 3, 2, 1]));
-
Instance commentary
-
Stack sequence for 1,2,3,4,5
out of stack sequence for 4,5,3,2,1
-
First traversal, obviously 1
not equal to 4
continue traversal, traverse 4 times to the secondary stack of the stack element is 1,2,3,4
stack top element is 4
when
-
Bring up the top element of the auxiliary stack, the stack element will be left to 5 /code>
-
At this point the stack element of the secondary stack is 3
on the top of the stack, and obviously 3
is not equal to the stack element 5
, we continue to traverse the 5
into the secondary stack
-
Just when the stack element is the same as 5
and the top element of the stack, so we pop up the top element of the stack, and the stack element becomes 3
-
To continue, the top element of the stack is now 3
the same as the stack element, pop up the top element of the stack
-
This time the top element of the stack becomes 2
, and the stack element becomes 2 /code>, continue to pop the top of the stack
-
When the top element of the stack changes to 1
, the stack element becomes 1
, the top element of the stack pops up
-
Because the secondary stack is now empty Jump out while
-
Because the stack element is at this point to all enter the secondary stack out for
-
Secondary stack eventually empty, program end