用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例1:
输入: ["CQueue","appendTail","deleteHead","deleteHead"] [[],[3],[],[]] 输出:[null,null,3,-1]
示例2:
输入: ["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"] [[],[],[5],[2],[],[]] 输出:[null,-1,null,null,5,2]
解题思路:
- 栈的特点:先进后出;队列的特点:先进先出;
- 如果使用栈实现队列,就要保证先进先出的特点。
- 一个队列为push队列,一个队列为pop队列,当每次要进行pop时,将存储队列重置。
- pop队列不为空时,不往队列中添加内容
package Algriothm; import java.util.Stack; public class CQueue { public static void main(String[] args) { CQueue cQueue = new CQueue(); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); cQueue.appendTail(20); System.out.println(cQueue.deleteHead()); cQueue.appendTail(1); cQueue.appendTail(8); cQueue.appendTail(20); cQueue.appendTail(1); cQueue.appendTail(11); cQueue.appendTail(2); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); System.out.println(cQueue.deleteHead()); } Stack<Integer> stack1; Stack<Integer> stack2; public CQueue() { stack1 = new Stack(); stack2 = new Stack(); } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { if (stack2.size() != 0) { return stack2.pop(); } if (stack1.size() == 0) { return -1; } while (stack1.size() != 0) { stack2.push(stack1.pop()); } return stack2.pop(); } }