Two queues generate a stack

package  queue;

 

/**

 * Two queues implement a stack

 *

 * Ideas: At least one of queue 1 and queue 2 is empty at any time, that is, if there are elements, all elements can only be in one queue. When an element needs to be inserted, insert the element into

 *  In an empty queue , and transfer all the elements of another non-empty queue to this queue, so the inserted elements are added to the front of the column

 *

 * @author Administrator

 *

 */

publicclass Stack { 

Queue queue1 = new Queue();

Queue queue2 = new Queue();

/**

 * Judgment is not empty

 * @return

 */

publicboolean isEmpty(){ 

returnqueue1.isEmpty() && queue2.isEmpty(); 

}

/**

 * add element

 */

publicvoid push(intdata){  

if(queue1.isEmpty()){

queue1.push(data);

while(!queue2.isEmpty()){

queue1.push(queue2.pop());

}

}else{

queue2.push(data);

while(!queue1.isEmpty()){

queue2.push(queue1.pop());

}

}

}

/**

 * 从栈取元素

 * @return

 */

public Integer pop(){

if(queue1.isEmpty()&&queue2.isEmpty()){

return null;

}

if(!queue1.isEmpty()){

return queue1.pop();

}else{

return queue2.pop();

}

}

/**

 * 取峰值

 * @return

 */

public Integer peek(){

if(queue1.isEmpty()&&queue2.isEmpty()){

return null;

}

if(!queue1.isEmpty()){

return queue1.peek();

}else{

return queue2.peek();

}

}

/**

 * 主函数

 * @param args

 */

public static void main(String[] args) {

Stack stack = new Stack();

stack.push(1);

stack.push(2);

stack.push(3);

stack.push(4);

while(!stack.isEmpty()){

System.out.println(stack.pop());

}

}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326048775&siteId=291194637