private Stack<Integer> s1;
private Stack<Integer> s2;
public MyQueue3() {
s1 = new Stack<>();
s2 = new Stack<>();
}
public void push(int x ){ //加入元素
s1.push(x);
}
public int pop() { //弹出元素
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.pop());
}
}
if (!s2.empty()) {
return s2.pop();
}
return -1;
}
public int peek() { //显示队头元素;
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.pop());
}
}
if (!s2.empty()) {
return s2.peek();
}
return -1;
}
public boolean empty() { //判断队是否是空;
if(s1.empty() && s2.empty()){
return true;
}
return false;
}
用栈实现队列(Java实现)
最新推荐文章于 2023-06-30 19:32:14 发布