100 question _ 24 stack push and pop Sequence

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.