首页 > 其他 > 详细

Implement Stack using Queues 解答

时间:2015-10-09 07:00:30      阅读:250      评论:0      收藏:0      [点我收藏+]

Question

Implement 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).

Solution

Java Queue Interface

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!