Enter Two integer sequences. One sequence represents the push sequence of the stack and determines whether the other sequence may be in the pop sequence. For the sake of simplicity, we assume that any two integers in the push sequence are not equal. For example, if the input push sequence is 1, 2, 3, 4, 5, 3, 2, and 1, it may be a pop series. It can have the following push and pop sequences: Push 1, Push 2, Push 3, Push 4, Pop, Push 5, pop, the pop sequence is 4, 5, 3, 2, and 1. However, sequences 4, 3, 5, 1, and 2 cannot be pop sequences of push sequences 1, 2, 3, 4, and 5.
This problem can be implemented using an auxiliary stack. The process is very simple, but it may be difficult to describe it.Code.
# Include <iostream>
# Include <stack>
Using namespace STD;
Bool isstackpushpop (IntA [],IntB [],IntN)
{
Stack <Int> MS;
IntI =-1, j = 0;
While(I <n & J <n)
{
If(Ms. Empty () | MS. Top ()! = B [J])
Ms. Push (A [++ I]);
Else{Ms. Pop (); j ++ ;}}ReturnMs. Empty ();
}
IntMain ()
{
IntA [] = {1, 2, 4, 5 };
IntB [] = {5, 4, 2, 3, 1 };
Cout <isstackpushpop (A, B, 5) <Endl;
Return0;
}