Professional Documents
Culture Documents
{
input(n)
input(permutation of n numbers in array A) // elements of A
are A[1],,A[n]
string s1 = enqueue(Q2, dequeue(Q1))
string s2 = push(S, dequeue(Q1))
string s3 = enqueue(Q2, pop(S))
function f1 (input = nothing; output = boolean value) //
return true if A is a stack permutation, false otherwise
{
define x = (initially) empty stack
int b = 1
for (int i=1; i<=n; ++i)
{
if(A[i] > b)
{
for (int j=b; j<A[i]; ++j)
{
x.push(j)
}
b = A[i]+1
}
else if (A[i] == b)
{
b++
}
else
{
int c = x.pop()
if (A[i] != c)
{
return false
exit out of function
}
}
}
}
return true
stack permutation
{
int b = 1;
int c = x.pop()
if (A[i] != c)
{
print(The number A[i] in the
permutation is the wrong place. The next element in the stack
was c. Therefore, in place of
A[i] we should have either c or
b(if b<=n))
exit out of function
}
}
}
}
if(f1())
{
f2()
}
else
{
f3()
}
}