//队列实现栈
class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
private int size;
/** Initialize your data structure here. */
public MyStack() {
this.queue1 = new LinkedList<Integer>();
this.queue2 = new LinkedList<Integer>();
this.size = 0;
}
/** Push element x onto stack. */
public void push(int x) {
if(queue1.peek() != null){
queue1.offer(x);
}else if(queue2.peek() != null){
queue2.offer(x);
}else{
//都为空,则用queue1开始
queue1.offer(x);
}
size++;
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(empty()){
throw new RuntimeException("无数据");
}
int e = 0;
if(queue2.peek() != null){
for(int i = 0; i < size - 1; i++){
queue1.offer(queue2.poll());
}
e = queue2.poll();
}else{
for(int i = 0; i < size - 1; i++){
queue2.offer(queue1.poll());
}
e = queue1.poll();
}
this.size--;
return e;
}
/** Get the top element. */
public int top() {
if(empty()){
throw new RuntimeException("无数据");
}
int e = 0;
if(queue2.peek() != null){
for(int i = 0; i < size; i++){
e = queue2.poll();
queue1.offer(e);
}
}else{
for(int i = 0; i < size; i++){
e = queue1.poll();
queue2.offer(e);
}
}
return e;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return size == 0;
}
public int size(){
return this.size;
}
}
//栈实现队列
class MyQueue {
Stack <Integer> stack = new Stack<Integer>();
Stack <Integer> stackTemp = new Stack<Integer>();
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(stackTemp.empty()) {
while(!stack.empty()){
stackTemp.push(stack.pop());
}
}
int temp = 0;
if(!stackTemp.empty()) {
temp = stackTemp.pop();
}
/*
while(!stackTemp.isEmpty()){
stack.push(stackTemp.pop());
}*/
return temp;
}
/** Get the front element. */
public int peek() {
while(!stack.empty()){
stackTemp.push(stack.pop());
}
int temp = stackTemp.peek();
while(!stackTemp.empty()){
stack.push(stackTemp.pop());
}
return temp;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return stackTemp.empty() && stack.empty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
队列实现栈,栈实现队列
最新推荐文章于 2023-03-23 17:53:53 发布