Programmer interview question selection (48): Two stack simulation queue C ++ code implementation

Source: Internet
Author: User

The Code is as follows:

# Include <iostream>

Using namespace STD;

Class zstackqueue
{
Public:
Class zstack
{
Public:
Zstack (INT size );
~ Zstack ();

Int POP ();
Void push (int e );
Bool empty () {return Top = 0 ;}

PRIVATE:
Int * s;
Int top;
Int size;
};
 
Public:
Zstackqueue (int n): S1 (N), S2 (n ){}
Void enqueue (int e );
Int dequeue ();

PRIVATE:
Zstack S1, S2;
};

Zstackqueue: zstack (int n)
: S (0), top (0), size (N)
{
S = new int [size] ();
}

Zstackqueue: zstack ::~ Zstack ()
{
If (s)
{
Delete [] S;
S = 0;
}
 
Top = 0;
Size = 0;
}

Int zstackqueue: zstack: Pop ()
{
If (top> 0)
Return s [-- top];
Else
Return ~ 0;
}

Void zstackqueue: zstack: Push (int e)
{
If (top <size)
S [top ++] = E;
}

Void zstackqueue: enqueue (int e)
{
S1.push (E );
}

Int zstackqueue: dequeue ()
{
If (! S2.empty ())
{
Return s2.pop ();
}
Else
{
While (! S1.empty ())
S2.push (s1.pop ());

Return s2.pop ();
}
}
Int main ()
{
Zstackqueue Q (3 );
Q. enqueue (5 );
Q. enqueue (2 );
Q. enqueue (8 );
Cout <q. dequeue () <"/t"; // <q. dequeue () <"/t" <q. dequeue () <Endl; // if this is the case, the output result will lead you to think that this is not a stack. Which is a queue! Oh, the reason is that hero knows everything!
Cout <q. dequeue () <"/t ";
Cout <q. dequeue () <"/t ";
Return 0;
}

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.