leetcode--Implement Stack using Queues

来源:互联网 发布:网络赚钱的门路和技巧 编辑:程序博客网 时间:2024/06/06 20:44

mplement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.
Notes:
  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
  • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.

[java] view plain copy
  1. class MyStack {  
  2.     Queue<Integer> queue1 = new LinkedList<Integer>();  
  3.     Queue<Integer> queue2 = new LinkedList<Integer>();  
  4.     boolean turn = true;  
  5.     // Push element x onto stack.  
  6.     public void push(int x) {  
  7.         if(turn){  
  8.             queue1.add(x);  
  9.         }else{  
  10.             queue2.add(x);  
  11.         }  
  12.     }  
  13.   
  14.     // Removes the element on top of the stack.  
  15.     public void pop() {  
  16.         if(turn){  
  17.             while(queue1.size()>1){  
  18.                 queue2.add(queue1.poll());  
  19.             }  
  20.             queue1.poll();  
  21.         }else{  
  22.             while(queue2.size()>1){  
  23.                 queue1.add(queue2.poll());  
  24.             }  
  25.             queue2.poll();  
  26.         }  
  27.         turn = !turn;  
  28.     }  
  29.   
  30.     // Get the top element.  
  31.     public int top() {  
  32.         if(turn){  
  33.             while(queue1.size()>1){  
  34.                 queue2.add(queue1.poll());  
  35.             }  
  36.             return queue1.peek();  
  37.         }else{  
  38.             while(queue2.size()>1){  
  39.                 queue1.add(queue2.poll());  
  40.             }  
  41.             return queue2.peek();  
  42.         }  
  43.     }  
  44.   
  45.     // Return whether the stack is empty.  
  46.     public boolean empty() {  
  47.         return queue1.isEmpty()&&queue2.isEmpty();  
  48.     }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46581183

原创粉丝点击