leetcode Implement Queue using Stacks

Implement Queue using Stacks 题目:https://leetcode.com/problems/implement-queue-using-stacks/

Implement Queue using Stacks

解题思路:

设有两个栈A和栈B,

push:每次添加新元素时,都放入栈A中,

pop:每次需要从B中取元素。一旦B栈中没有可取元素了,就将A中所有元素压入栈B中,假设元素压入栈A顺序是:1,2,3,4,5,从左到右对应先后次序,如果从栈A中取出,则是5,4,3,2,1(即先取5,最后取1),然后再放入栈B中,则在栈B中的元素顺序为5,4,3,2,1,再从栈B取出元素,则后进先出,即依次取出1,2,3,4,5,从而总体形成了一个(1)先进(1)先出的队列顺序。

peek();与pop 原理相同

empty():判断两个栈是否都为空。
 

class MyQueue {

	Stack<Integer> stack=new Stack<>();
	Stack<Integer> stack2=new Stack<>();
	/** 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() {
		while(stack2.isEmpty()){
			while(!stack.isEmpty()){
				int temp=stack.peek();
				stack.pop();
				stack2.push(temp);
			}
		}
		return stack2.pop();
	}

	/** Get the front element. */
	public int peek() {
		while(stack2.isEmpty()){
			while(!stack.isEmpty()){
				int temp=stack.peek();
				stack.pop();
				stack2.push(temp);
			}
		}
		return stack2.peek();
	}

	/** Returns whether the queue is empty. */
	public boolean empty() {
		return stack2.isEmpty() && stack.isEmpty();
	}
}

猜你喜欢

转载自blog.csdn.net/u011243684/article/details/84872619