Queue is a typical FIFO data structure, there are many ways to implement the queue, such as arrays, such as linked lists, queues can also be implemented with two stacks, the following two stacks to implement a queue.
Principle
Two stacks, a stack used to queue, called him the stack, the other stack for the team, called out of the team stack.
When we are in the queue, we push elements directly into the stack.
When you are out of the team, there are two types of situations:
① If the team stack is not empty, then directly out of the stack stack top element
② if the stack is empty, the queued stack elements are stacked and pushed out of the queue stack, then out of the stack
Specific implementation
Knowing the principle, the implementation is very simple, here we use the Java.util.stack class in the JDK as the stack in our queue, the JDK implementation of this stack inherits the vector class, so his bottom is also used in the array.
The code is as follows
Package Com.gdut.ds.queue;import java.util.stack;/** * Two stacks for queue */public class Queue<t> {/** * queued stack */private STACK&L T t> instack = new stack<t> ()/** * Outbound Stack */private stack<t> outstack = new stack<t> ();/** * Queue Size */priva Te int size;/** * enqueued */public void Enqueue (T obj) {instack.push (obj); size++;} /** * Out team * @return */public T dequeue () {T obj = null;if (Outstack.empty ()) {while (!instack.empty ()) {Outstack.push (instack). Pop ());}} obj = Outstack.pop (); Size--;return obj;} /** * Queue Size * @return */public int size () {return size;} /** * Queue is empty * @return */public Boolean empty () {return size = = 0;}}
Test
queue<string> queue =NewQueue<>(); Queue.enqueue ("Hello"); Queue.enqueue ("My"); Queue.enqueue ("Name"); Queue.enqueue (" is"); Queue.enqueue ("Yanghao"); System. out. println (Queue.size ()); while(!Queue.empty ()) {System. out. println (Queue.dequeue ()); }
The results are as follows
5 Hellomyname is Yanghao
The Stack class throws a emptystackexcep when there are no elements in the queue.
Java Stack Implementation queue