Topic:
Judge the legality of the elements ' stack and the order of the stack. such as: Into the stack sequence (1,2,3,4,5), the stack sequence for (4,5,3,2,1) is a legal sequence, into the stack sequence (1,2,3,4,5), the stack sequence for (1,5,3,2,4) is an illegal sequence.
The code implementation is as follows:
#include <iostream>
#include <assert.h>
#include <stack>
#include <Windows.h>
using namespace std;
Judge the legality of
bool Islegal (int* Stackin, int* stackout, int lenin, int lenout) //into stack sequence, out stack sequence, into stack length, out stack length
{
ASSERT (Stackin && stackout); First to determine the stack sequence, the stack sequence is not empty
if (Lenin!= lenout) //stack length and stack length is not equal, illegal
{return
false;
}
Stack<int> QQ;
int i = 0;
int j = 0;
for (; i < Lenin; ++i)
{
qq.push (stackin[i]); First the element one by one into the stack while
(qq.size () > 0 && qq.top () = = Stackout[j]) //The above code is in the stack, so the number of elements must be greater than 0, and each stack top and stack sequence one by one match, otherwise illegal
{
qq.pop ();
++j
}
}
Return (qq.size () = = 0)? True:false; When the program is running here, the stack should be empty or illegal
}
First sequence of test topics:
#include "Stack.h"
void Teststack ()
{
int stackin[] = {1, 2, 3, 4, 5}; into the stack sequence
int stackout[] = {4, 5, 3, 2, 1}; Out stack sequence
int lenin = sizeof (Stackin)/sizeof (stackin[0));
int lenout = sizeof (stackout)/sizeof (stackout[0));
int www = islegal (Stackin, Stackout, Lenin, Lenout);
if (www)
{
cout << "Out stack sequence legal" << Endl;
}
else
{
cout << "out stack sequence illegal" << Endl
}
}
int main ()
{
teststack ();
System ("pause");
return 0;
}
Test a second sequence:
#include "Stack.h"
void Teststack ()
{
int stackin[] = {1, 2, 3, 4, 5}; into the stack sequence
int stackout[] = {1, 5, 3, 2, 4}; Out stack sequence
int lenin = sizeof (Stackin)/sizeof (stackin[0));
int lenout = sizeof (stackout)/sizeof (stackout[0));
int www = islegal (Stackin, Stackout, Lenin, Lenout);
if (www)
{
cout << "Out stack sequence legal" << Endl;
}
else
{
cout << "out stack sequence illegal" << Endl
}
}
int main ()
{
teststack ();
System ("pause");
return 0;
}