Implement the following operations of a stack using queues.
Notes:
push to back
, peek/pop from front
, size
, and is empty
operations are valid.Key to the solution is to use two queues. Queue is strictly First In, First Out.
1 class MyStack { 2 Queue<Integer> queue1; 3 Queue<Integer> queue2; 4 5 public MyStack(){ 6 queue1 = new LinkedList<Integer>(); 7 queue2 = new LinkedList<Integer>(); 8 } 9 10 // Push element x onto stack. 11 public void push(int x) { 12 queue1.add(x); 13 } 14 15 // Removes the element on top of the stack. 16 public void pop() { 17 if (queue1.peek() == null) 18 return; 19 int length = queue1.size(); 20 queue2 = new LinkedList<Integer>(); 21 while (length > 1) { 22 queue2.add(queue1.remove()); 23 length--; 24 } 25 queue1 = queue2; 26 } 27 28 // Get the top element. 29 public int top() { 30 if (queue1.peek() == null) 31 return -1; 32 queue2 = new LinkedList<Integer>(); 33 int length = queue1.size(); 34 int lastElement = 0; 35 while (length > 0) { 36 lastElement = queue1.remove(); 37 queue2.add(lastElement); 38 length--; 39 } 40 queue1 = queue2; 41 return lastElement; 42 } 43 44 // Return whether the stack is empty. 45 public boolean empty() { 46 if (queue1.peek() == null) 47 return true; 48 return false; 49 } 50 }
Implement Stack using Queues 解答
原文:http://www.cnblogs.com/ireneyanglan/p/4862789.html