标签:先进先出 structure you ast integer for queue 就是 init
怎么用栈实现队列?import java.util.ArrayList;
public class MyQueue {
private ArrayList<Integer> in;
private ArrayList<Integer> out;
public MyQueue() {
in = new ArrayList<Integer>();
out = new ArrayList<Integer>();
}
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<Integer> 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();
}
}
标签:先进先出 structure you ast integer for queue 就是 init
原文地址:https://blog.51cto.com/14232658/2447446