用队列实现栈(JAVA)
•
编程语言
仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
- void push(int x) 将元素 x 压入栈顶。
- int pop() 移除并返回栈顶元素。
- int top() 返回栈顶元素。
- boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
class MyStack {
private Queue q1;
private Queue q2;
public MyStack() {
q1 = new LinkedList<>();
q2 = new LinkedList<>();
}
public void push(int x) {
if(!q1.isEmpty()) {
q1.offer(x);
}else {
q2.offer(x);
}
}
public int pop() {
if(empty()) {
return -1;
}
//找到不为空的队列,转移size-1个元素
if(!q1.isEmpty()) {
int size = q1.size();
for(int i = 0; i < size - 1; i++) {
q2.offer(q1.poll());
}
return q1.poll();
}else {
int size = q2.size();
for(int i = 0; i < size - 1; i++) {
q1.offer(q2.poll());
}
return q2.poll();
}
}
public int top() {
if(empty()) {
return -1;
}//“出栈”时出不为空的队列,出size-1个元素,剩下的元素就是要出栈的元素
if(!q1.isEmpty()) {
int size = q1.size();
int tmp = -1;
for(int i = 0; i < size; i++) {
tmp = q1.poll();
q2.offer(tmp);
}
return tmp;
}else {
int size = q2.size();
int tmp = -1;
for(int i = 0; i < size; i++) {
tmp = q2.poll();
q1.offer(tmp);
}
return tmp;
}
}
public boolean empty() {
return q1.isEmpty() && q2.isEmpty();
}
}
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/c96875c7a8.html
