本文主要是介绍Day10|栈与队列part01:232.用栈实现队列、225.用队列实现栈,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
232. 用栈实现队列
使用两个栈,注意pop和peek:
class MyQueue {private Stack<Integer> stackIn;private Stack<Integer> stackOut;public MyQueue() {stackIn = new Stack<>();stackOut = new Stack<>();}public void push(int x) {stackIn.push(x);}/** Removes the element from in front of queue and returns that element. */public int pop() {dumpstackIn();return stackOut.pop();}/** Get the front element. */public int peek() {dumpstackIn();return stackOut.peek();}/** Returns whether the queue is empty. */public boolean empty() {return stackIn.isEmpty() && stackOut.isEmpty();}// 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中private void dumpstackIn(){if (!stackOut.isEmpty()) return;while (!stackIn.isEmpty()){stackOut.push(stackIn.pop());}}
}
(这里记得在构造器中java要把两个栈实例化,cpp不用)
225. 用队列实现栈
class MyStack {Queue<Integer> queue;public MyStack() {queue = new LinkedList<>();}public void push(int x) {queue.add(x);}public int pop() {int len = queue.size();while(len > 1){queue.add(queue.poll());len--;}return queue.poll();}public int top() {int topElement = pop();queue.add(topElement);return topElement;}public boolean empty() {return queue.isEmpty();}
这篇关于Day10|栈与队列part01:232.用栈实现队列、225.用队列实现栈的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!