标签:
As the title described, you should only use two stacks to implement a queue‘s actions.
The queue should support push(element)
, pop()
and top()
where pop is pop the first(a.k.a front) element in the queue.
Both pop and top methods should return the value of first element.
push(1)
pop() // return 1
push(2)
push(3)
top() // return 2
pop() // return 2
1 public class Queue { 2 private Stack<Integer> stack1; 3 private Stack<Integer> stack2; 4 5 public Queue() { 6 // do initialization if necessary 7 stack1 = new Stack<Integer>(); 8 stack2 = new Stack<Integer>(); 9 } 10 11 public void push(int element) { 12 stack1.push(element); 13 } 14 15 public int pop() { 16 if (stack2.size() != 0) { 17 return stack2.pop(); 18 } 19 20 while (stack1.size() != 0) { 21 stack2.push(stack1.pop()); 22 } 23 24 if (stack2.size() != 0) { 25 return stack2.pop(); 26 } 27 return -1; 28 } 29 30 public int top() { 31 32 if (stack2.size() != 0) { 33 return stack2.peek(); 34 } 35 while (stack1.size() != 0) { 36 stack2.push(stack1.pop()); 37 } 38 39 if (stack2.size() != 0) { 40 return stack2.peek(); 41 } 42 return -1; 43 } 44 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5683314.html