队列与栈的相互实现
1 队列实现栈
实现思路:采用两个队列来实现,第一次入栈放在两个队列中的一个内,后续放在不为空的那个队列中。出栈时将不为空的哪个队列逐一出队列放在空队列中,然后出队列即可。
class MyStack {
private Queue<Integer> myQueue1;
private Queue<Integer> myQueue2;
private int usedSize;
/** Initialize your data structure here. */
public MyStack() {
myQueue1=new LinkedList<>();
myQueue2=new LinkedList<>();
this.usedSize=0;
}
/** Push element x onto stack. */
public void push(int x) {
if (!myQueue1.isEmpty()){
myQueue1.add(x);
}else if(!myQueue2.isEmpty()){
myQueue2.add(x);
}else {
myQueue1.add(x);
}
this.usedSize++;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(empty()){
return -1;
}
int data;
if(!myQueue1.isEmpty()){
for (int i = 0; i <this.usedSize-1;i++) {
myQueue2.add(myQueue1.poll());
}
data = myQueue1.poll();
}else {
for (int i = 0; i <this.usedSize-1;i++) {
myQueue1.add(myQueue2.poll());
}
data = myQueue2.poll();
}
this.usedSize--;
return data;
}
/** Get the top element. */
public int top() {
if(empty()){
return -1;
}
int data = 0;
if(!myQueue1.isEmpty()) {
for (int i = 0; i < this.usedSize; i++) {
data = myQueue1.poll();
myQueue2.add(data);
}
}else {
for (int i = 0; i < this.usedSize; i++) {
data = myQueue2.poll();
myQueue1.add(data);
}
}
return data;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return usedSize==0;
}
}
2 栈实现队列
实现思路:两个栈实现队列,入队列统一放入第一个栈中,出队列从第二个栈出队列,如果第二个栈为空,将第一个栈中的所有值放在第二个栈中。
class MyQueue {
private Stack<Integer> myStack1;
private Stack<Integer> myStack2;
private int usedSize;
/** Initialize your data structure here. */
public MyQueue() {
myStack1=new Stack<>();
myStack2=new Stack<>();
this.usedSize=0;
}
/** Push element x to the back of queue. */
public void push(int x) {
myStack1.push(x);
usedSize++;
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(myStack2.isEmpty()&&myStack1.isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
if(!myStack2.isEmpty()){
usedSize--;
return myStack2.pop();
}else {
while (!myStack1.isEmpty()){
myStack2.push(myStack1.pop());
}
usedSize--;
return myStack2.pop();
}
}
/** Get the front element. */
public int peek() {
if(myStack2.isEmpty()&&myStack1.isEmpty()){
throw new UnsupportedOperationException("队列为空");
}
if(!myStack2.isEmpty()){
return myStack2.peek();
}else {
while (!myStack1.isEmpty()){
myStack2.push(myStack1.pop());
}
return myStack2.peek();
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
return this.usedSize==0;
}
}