题目一
两个栈实现队列
使用两个栈,一个栈专门add数据,一个栈专门poll数据
public class MyQueue<T> {
private Stack<T> addStack = new Stack<T>();
private Stack<T> popStack = new Stack<T>();
public MyQueue() {
}
public boolean add(T t) {
return addStack.push(t) == t;
}
public boolean isEmpty() {
return addStack.isEmpty() && popStack.isEmpty();
}
public T poll() {
if (popStack.empty()) {
while (!addStack.empty())
popStack.push(addStack.pop());
}
return popStack.pop();
}
}
题目二
两个队列实现栈
public class MyStack<T> {
private Queue<T> from = new ArrayDeque<T>();
private Queue<T> to = new ArrayDeque<T>();
public MyStack() {}
public T push(T t) {
from.add(t);
return t;
}
public boolean isEmpty() {
return from.isEmpty() && to.isEmpty();
}
public T pop() {
if (from.isEmpty()) {
return null;
}
while (from.size() > 1) {
to.add(from.poll());
}
while (!to.isEmpty()) {
from.add(to.poll());
}
return from.poll();
}
weixin_43820398
发布了7 篇原创文章 · 获赞 0 · 访问量 302
私信
关注