leetcode--Implement Stack using Queues

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值