225. Implement Stack using Queues

时间:2017-10-24 21:52:07   收藏:0   阅读:243

Implement the following operations of a stack using queues.

Notes:

题目含义:使用queue来实现stack的功能

 

 1 class MyStack {
 2 
 3     private Queue<Integer> p = new LinkedList<>();
 4 
 5     /** Initialize your data structure here. */
 6     public MyStack() {
 7 
 8     }
 9 
10     /** Push element x onto stack. */
11     public void push(int x) {
12         p.add(x);
13         for (int i=1;i<p.size();i++)
14         {
15             p.add(p.poll());
16         }
17     }
18 
19     /** Removes the element on top of the stack and returns that element. */
20     public int pop() {
21         return p.poll();
22     }
23 
24     /** Get the top element. */
25     public int top() {
26         return p.peek();
27     }
28 
29     /** Returns whether the stack is empty. */
30     public boolean empty() {
31         return p.isEmpty();
32     }
33 }

 

原文:http://www.cnblogs.com/wzj4858/p/7725653.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!