Two stacks implement one queue and two stacks implement queues.
# Include
# Include
Using namespace std ;?
Template
Class Queue
{
Public:
Queue ();
~ Queue ();
Void Inqueue (const T & item );
Bool isEmpty ();
T DeleteHead ();
Private:
Stack Stack1;
Stack Stack2;
};
Template
Queue : Queue ()
{
Cout <"constuct queue" <endl;
}
Template
Queue ::~ Queue ()
{
Cout <"destroy constuct queue" <endl;
}
Template
Void Queue : Inqueue (const T & item)
{
Stack1.push (item );
}
Template
T Queue : DeleteHead ()
{
If (stack2.empty ())
{
If (stack1.empty ())
{
Cout <"queue is NULL" <endl;
}
While (! Stack1.empty ())
{
T elem = stack1.top ();
Stack1.pop ();
Stack2.push (elem );
}
}
// Else? ? ? ? ? ? ? // Do not add else ?, The type of the first T is uncertain; the second does not work when the first call deletes a function.
//{
T temp = stack2.top ();
Stack2.pop ();
//}
? ? Return temp;
}
Template
Bool Queue : IsEmpty ()
{
If (stack2.empty () & stack1.empty ())
Return true;
Else
Return false;
}
Int main ()
{
Queue Q;
While (1)
{
Int data = 0;
Cin> data;
If (data = 0) break;
Q. Inqueue (data );
}
While (! Q. isEmpty ())
{
Int va = q. DeleteHead ();
Cout <va <endl;
}
System ("pause ");
Return 0;
}