Title: Enter a sequence of two integers. One of these sequences represents the push order of the stack,
Determine if another sequence is possible for the corresponding pop sequence.
For simplicity's sake, let's assume that any two integers in the push sequence are not equal.
Like what:
The input push sequence is 1,2,3,4,5, then 4,5,3,2,1 may be a pop sequence.
Because you can have the following push and pop sequences:
Push 1, Push 2, Push 3, push 4, pop, push 5, pop, pop, pop, pop
The resulting pop sequence is 4,5,3,2,1.
However, sequence 4,3,5,1,2 cannot be the pop sequence of the push sequence 1,2,3,4,5. Because I can simulate the following:
Push 1, Push 2, Push 3, push 4, Pop (4), pop (3), push 5, Pop (5), pop (2)---> less than 1
Analysis:
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
In the example we can see the process of judging, we can simulate the process with the program.
See Code implementation:
#include <iostream> using namespace std;
Template<int maxsize=1024> class stack{private:int data[maxsize];
int POS;
Public:stack ():p OS (0) {} bool Empty () {return pos = 0;
BOOL Full () {return pos = = MAXSIZE;
the bool Get (int& _value) {if (empty ()) is return false;
_value = data[pos-1];
return true;
BOOL Pop (int& _value) {if (empty ()) return false;
_value = Data[--pos];
return true;
The bool push (int& _value) {if (full)) is return false;
Data[pos] = _value;
POS + +;
return true;
}
}; BOOL Truesequence(int* push_str,int len, int* pop_str)
{if (len = = 0) return true;
int i = 0;
int j = 0;
Stack<1024> s;
while (I < len) {int V;
if (J < len && Pop_str[i] = = Push_str[j]) {i + +;
j + +;
Continue
} else {if (S.get (v)) { if (v!= Pop_str[i]) {if (
J >= Len) break;
S.push (Push_str[j]);
j + +;
} else { S.pop (v);
i + +; } else {I
F (J >= Len) break;
S.push (Push_str[j]);
j + +;
}} if (i = = j) return true;
else return false;
int main () {int push1[5] = {1,2,3,4,5};
int pop1[5] = {4,5,3,2,1}; if (Truesequence (PUSH1, 5, POP1)) cout << "Push sequence:1 2,3,4,5;
4,5,3,2,1 is a pop sequence "<< Endl; else cout << "Push sequence:1 2,3,4,5;
4,5,3,2,1 is not a pop sequence "<< Endl;
int pop2[5] = {4,3,5,1,2}; if (truesequence(PUSH1, 5, POP2)) cout << "Push sequence:1 2,3,4,5;
4,3,5,1,2 is a pop sequence "<< Endl; else cout << "Push sequence:1 2,3,4,5;
4,3,5,1,2 is not a pop sequence "<< Endl;
return 0; }
The output results are:
Push Sequence:1 2,3,4,5; 4,5,3,2,1 is a pop sequence
Push Sequence:1 2,3,4,5; 4,3,5,1,2 is not a pop sequence
Author: csdn Blog hhh3h