【LeetCode232】 Implement Queue using Stacks★
1.题目描述
2.思路
思路简单,这里用一个图来举例说明:
3.java代码
1 public class MyQueue { 2 3 Stack<Integer> stack1=new Stack<Integer>(); 4 Stack<Integer> stack2=new Stack<Integer>(); 5 6 /** Push element x to the back of queue. */ 7 public void push(int x) { 8 stack1.push(x); 9 } 10 11 /** Removes the element from in front of queue and returns that element. */ 12 public int pop() { 13 if(!stack2.isEmpty()) 14 return stack2.pop(); 15 else{ 16 while(!stack1.empty()) 17 stack2.push(stack1.pop()); 18 return stack2.pop(); 19 } 20 } 21 22 /** Get the front element. */ 23 public int peek() { 24 if(!stack2.isEmpty()) 25 return stack2.peek(); 26 else{ 27 while(!stack1.empty()) 28 stack2.push(stack1.pop()); 29 return stack2.peek(); 30 } 31 } 32 33 /** Returns whether the queue is empty. */ 34 public boolean empty() { 35 return stack1.empty()&&stack2.empty(); 36 } 37 } 38 39 /** 40 * Your MyQueue object will be instantiated and called as such: 41 * MyQueue obj = new MyQueue(); 42 * obj.push(x); 43 * int param_2 = obj.pop(); 44 * int param_3 = obj.peek(); 45 * boolean param_4 = obj.empty(); 46 */