Home > Back-end >  Implement a queue by two stack (not original)
Implement a queue by two stack (not original)

Time:10-20

No matter if StackA (the most began to add element of the stack) to StackB medium voltage into the elements, you must select a one-time all pumped,

Whenever you take elements from the queue, must ensure that the elements pop out from StackB, that is to say, when StackB not empty can never again to StackB medium voltage into the element,
In the deposit element has to deposit, in StackA take elements from the StackB take, but shall take note of the time need to make sure that when StackB is empty, you first will StackA elements in one time as StackB, during operation, from StackB

Public static class TwoStackQueue {
Private Stack StackA;
Private Stack StackB;

Public TwoStackQueue () {
StackA=new Stack<> (a);
StackB=new Stack<> (a);
}

/* *
* add a logic element
* @ param e to add the element
* @ return here just follow the habit of Queue here easy handling returns true
*/
Public Boolean add (E, E) {
StackA. Push (e);
return true;
}

/* *
* remove elements you need to determine when two places, StackA & amp; StackB are empty
* StackB for empty, all the elements in the StackA in turn pressure into the StackB
* @ return to return the elements in the queue if the queue is empty return null
*/
Public E poll () {
//no element is returned directly if the queue empty, an exception can choose
If (stackB. IsEmpty () & amp; & StackA. IsEmpty ()) {
return null;
}

{if (stackB. IsEmpty ())
while (! StackA. IsEmpty ()) {
StackB. Add (stackA. Pop ());
}
}

Return stackB. Pop ();
}

/* *
* peek operation does not remove the element, only returns the queue in the head element value
* @ the element value of return queue head
*/
Public E peek () {
//no element is returned directly if the queue empty, an exception can choose
If (stackB. IsEmpty () & amp; & StackA. IsEmpty ()) {
return null;
}

{if (stackB. IsEmpty ())
while (! StackA. IsEmpty ()) {
StackB. Add (stackA. Pop ());
}
}

Return stackB. Peek ();
}
}
  • Related