用两个栈来实现队列
作者:互联网
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.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();
}
}
}
没错我就是灵魂画手!
public static void main(String[] args) {
newQueue N = new newQueue();
N.add(1);
N.add(2);
N.add(3);
N.add(4);
N.add(5);
int peek1 = N.peek();
System.out.println(peek1);
N.pop();
N.pop();
int peek2 = N.peek();
System.out.println(peek2);
}
标签:int,队列,s2,s1,pop,实现,add,isEmpty,栈来 来源: https://blog.csdn.net/qq_41409907/article/details/89320297