怎么用栈实现队列?
队列的特点是:先进先出
可以用两个栈实现,将栈A的栈顶元素出栈,再压入栈B。循坏该动作,直到A栈为空。这时栈B的栈顶元素就是队首元素。栈B中元素依次出栈即出队列。
创新互联是一家集网站建设,隆回企业网站建设,隆回品牌网站建设,网站定制,隆回网站建设报价,网络营销,网络优化,隆回网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
import java.util.ArrayList;
public class MyQueue {
private ArrayList in;
private ArrayList out;
public MyQueue() {
in = new ArrayList();
out = new ArrayList();
}
public void push(int x) {
in.add(x);
}
public int pop() {
if (out.isEmpty()) {
int size = in.size();
for (int i = 0; i < size; i++) {
int v = in.remove(in.size() - 1);
out.add(v);
}
}
return out.remove(out.size() - 1);
}
public int peek() {
if (out.isEmpty()) {
int size = in.size();
for (int i = 0; i < size; i++) {
int v = in.remove(in.size() - 1);
out.add(v);
}
}
return out.get(out.size() - 1);
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
怎么用队列实现栈?
栈的特点是:先进后出
调用队列的方法,取出队首元素尾插在队尾,如此循坏等价于逆序了队列。这时候的队首即是栈顶。
import java.util.LinkedList;
class MyStack {
private LinkedList queue;
/** Initialize your data structure here. */
public MyStack() {
queue = new LinkedList<>();
}
/** Push element x onto stack. */
public void push(int x) {
queue.addLast(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int size = queue.size();
for (int i = 0; i < size - 1; i++) {
int v = queue.pollFirst();
queue.addLast(v);
}
return queue.pollFirst();
}
/** Get the top element. */
public int top() {
int size = queue.size();
for (int i = 0; i < size - 1; i++) {
int v = queue.pollFirst();
queue.addLast(v);
}
int v = queue.pollFirst();
queue.addLast(v);
return v;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue.isEmpty();
}
}