标签:
Implement the following operations of a queue using stacks.
Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.
思路:
利用两个栈,每次入队的操作时,将一个栈中的元素全部弹出,后在有元素的栈中压入入队元素,后将该栈的全部元素弹出,压回第一个栈中即可。
解法:
1 import java.util.Stack; 2 3 public class MyQueue 4 { 5 private Stack<Integer> inputStack; 6 private Stack<Integer> outputStack; 7 8 public MyQueue() 9 { 10 inputStack = new Stack<>(); 11 outputStack = new Stack<>(); 12 } 13 14 public void push(int x) 15 { 16 while(!outputStack.isEmpty()) 17 inputStack.push(outputStack.pop()); 18 inputStack.push(x); 19 while(!inputStack.isEmpty()) 20 outputStack.push(inputStack.pop()); 21 } 22 23 public void pop() 24 { outputStack.pop(); } 25 26 public int peek() 27 { return outputStack.peek(); } 28 29 public boolean empty() 30 { return outputStack.isEmpty(); } 31 }
LeetCode 232 Implement Queue using Stacks
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5839325.html