用两个栈来实现队列
注意点:
当s2为空时 s1才能向s2倒数据,s1倒数据就要全部倒完
import java.util.Stack;
class newQueue{
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
public void add(int value) {
s1.push(value);
}
public int pop() {
if (s1.isEmpty() && s2.isEmpty()) {
return -1;
} else {
while (!s1.isEmpty() && s2.isEmpty()) {
s2.push(s1.pop());
}
return s2.pop();
}
}
public int peek() {
if (s1.isEmpty() && s2.isEmpty()) {
return -1;
} else {
while (!s1.isEmpty()) {
s2.push(s1.pop());
}
return s2.peek();
}
}
}
没错我就是灵魂画手!
两个队列实现栈
pop 两个队列 一个放数据一个空 当要弹出栈顶的时候 让这个队列中前几项放到空队列中 只留下需要弹出的数据 这个时候改变引用 help改成data
peek就是只返回给用户不弹出
public class TwoQueueStack {
private Queue<Integer> data;
private Queue<Integer> help;
public TwoQueueStack() {
data = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int value) { //全部放到data队列
data.add(value);
}
public int peek() {
if (data.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
while (data.size() != 1) { //不止一个数的时候放到help只留下最后一个数据
help.add(data.poll());
}
int res = data.poll();
help.add(res);
swap();
return res;
}
public int pop() {
if (data.isEmpty()) {
throw new RuntimeException("Stack is empty");
}
while (data.size() > 1) { //不止一个数的时候放到help
help.add(data.poll());
}
int res = data.poll();
swap();
return res;
}
public void swap() { //改变引用
Queue<Integer> temp = help;
help = data;
data = temp;
}
}