Lcof09

Lcof 09.用两个栈实现队列

用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

class CQueue {
Stack in;
Stack out;
int size;

public CQueue() {
in = new Stack<>();
out = new Stack<>();
size=0;
}

public void appendTail(int value) {
in.push(value);
size++;
}

public int deleteHead() {
if(size==0){
return -1;
}
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
size--;
return (int) out.pop();
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/

优化

因为Stack继承了Vector接口,而Vector底层是一个Object[]数组,所以要考虑空间扩容和移位的问题。 可以使用LinkedList来做Stack的容器,其本身结构是个双向链表,扩容消耗少。

class CQueue {
LinkedList<Integer> stack1;
LinkedList<Integer> stack2;

public CQueue() {
stack1 = new LinkedList<>();
stack2 = new LinkedList<>();
}

public void appendTail(int value) {
stack1.add(value);
}

public int deleteHead() {
if (stack2.isEmpty()) {
if (stack1.isEmpty()) return -1;
while (!stack1.isEmpty()) {
stack2.add(stack1.pop());
}
return stack2.pop();
} else return stack2.pop();
}
}

关系图

关系图

Author: Jiayi Yang
Link: https://jiayiy.github.io/2020/06/02/Lcof09/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.