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

LeetCode 232 Implement Queue using Stacks

时间:2016-09-04 15:55:07      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

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

 

思路:

利用两个栈,每次入队的操作时,将一个栈中的元素全部弹出,后在有元素的栈中压入入队元素,后将该栈的全部元素弹出,压回第一个栈中即可。

 

解法:

 1 import java.util.Stack;
 2 
 3 public class MyQueue
 4 {
 5     private Stack<Integer> inputStack;
 6     private Stack<Integer> outputStack;
 7 
 8     public MyQueue()
 9     {
10         inputStack = new Stack<>();
11         outputStack = new Stack<>();
12     }
13 
14     public void push(int x)
15     {
16         while(!outputStack.isEmpty())
17             inputStack.push(outputStack.pop());
18         inputStack.push(x);
19         while(!inputStack.isEmpty())
20             outputStack.push(inputStack.pop());
21     }
22 
23     public void pop()
24     { outputStack.pop(); }
25 
26     public int peek()
27     { return outputStack.peek(); }
28 
29     public boolean empty()
30     { return outputStack.isEmpty(); }
31 }

 

LeetCode 232 Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/wood-python/p/5839325.html

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