码迷,mamicode.com
首页 > 其他好文 > 详细

Implement Queue using Stacks 解答

时间:2015-10-09 07:03:58      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:

Question

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

Solution

 1 class MyQueue {
 2     Stack<Integer> stack1;
 3     Stack<Integer> stack2;
 4     
 5     public MyQueue() {
 6         stack1 = new Stack<Integer>();
 7         stack2 = new Stack<Integer>();
 8     }
 9     
10     // Push element x to the back of queue.
11     public void push(int x) {
12         stack1.push(x);
13     }
14 
15     // Removes the element from in front of queue.
16     public void pop() {
17         stack2 = new Stack<Integer>();
18         int length = stack1.size();
19         while (length > 1) {
20             stack2.push(stack1.pop());
21             length--;
22         }
23         stack1.pop();
24         length = stack2.size();
25         while (length > 0) {
26             stack1.push(stack2.pop());
27             length--;
28         }
29     }
30 
31     // Get the front element.
32     public int peek() {
33         stack2 = new Stack<Integer>();
34         int current = 0;
35         int length = stack1.size();
36         while (length > 0) {
37             current = stack1.pop();
38             stack2.push(current);
39             length--;
40         }
41         length = stack2.size();
42         while (length > 0) {
43             stack1.push(stack2.pop());
44             length--;
45         }
46         return current;
47     }
48 
49     // Return whether the queue is empty.
50     public boolean empty() {
51         return stack1.empty();
52     }
53 }

 

Implement Queue using Stacks 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4862802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!