用队列实现栈结构,可以用两个队列来实现。一个用来插入数据,一个用来辅助实现pop和push。push时直接把数放在第一个队列中,pop时,先把队列1里除了最后一个push进去的数全部push进队列2中,最后的元素就是我们要pop出的元素,pop出后再把队列2中的数再放进队列1中。获取栈顶元素和方法和pop的方法相同。
用栈实现队列结构,同样要用两个栈来实现。一个栈用来poll数据,一个用来push数据。push时,都把数放进栈1中。poll时,把栈1的数据都放进栈2中,再poll。获取栈顶元素的方式和poll的方法相同。
代码如下所示:
public class StackAndQueueConvert {
public static void main(String[] args) {
}
public static class TwoStacksQueue {
private Stack<Integer> stackPush;
private Stack<Integer> stackPop;
public void push(int pushInt) {
stackPush.push(pushInt);
}
public int poll() {
if(stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
} else if (stackPop.empty()) {
while(!stackPop.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.pop();
}
public int peek() {
if(stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
} else if(stackPop.isEmpty()) {
while(!stackPop.empty()) {
stackPop.push(stackPush.pop());
}
}
return stackPop.peek();
}
}
public static class TwoQueuesStack {
private Queue<Integer> queue;
private Queue<Integer> help;
public TwoQueuesStack() {
queue = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int pushInt) {
queue.add(pushInt);
}
public int peek() {
if(queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while(queue.size() != 1) {
help.add(queue.poll());
}
int res = queue.poll();
help.add(res);
swap();
return res;
}
public int pop() {
if(queue.isEmpty()) {
throw new RuntimeException("Stack is empty!");
}
while(queue.size() > 1) {
help.add(queue.poll());
}
int res = queue.poll();
swap();
return res;
}
private void swap() {
Queue<Integer> tmp = help;
help = queue;
queue = tmp;
}
}
}