232. Implement Queue using Stacks

本文介绍了两种使用栈实现队列的方法。方法一通过在入队时调整栈内元素顺序来实现;方法二则利用两个栈,分别作为输入栈和输出栈,通过在出队时从输入栈转移元素到输出栈来保持队列特性。

一、题目

  1、审题

  

  2、分析

    使用栈来实现队列的功能。

 

二、解答

  1、思路

    方法一、

      只修改 Pop 方法,使得栈中元素排序为队列的规则。

 1 public class MyQueue {
 2     
 3     Stack<Integer> stack;
 4     /** Initialize your data structure here. */
 5     public MyQueue() {
 6         stack = new Stack<>();
 7     }
 8     
 9     /** Push element x to the back of queue. */
10     public void push(int x) {
11         if(stack.isEmpty()) {
12             stack.push(x);
13         }
14         else {
15             Stack<Integer> tmp = new Stack<>();
16             while(!stack.isEmpty())
17                 tmp.push(stack.pop());
18             stack.push(x);
19             while(!tmp.isEmpty())
20                 stack.push(tmp.pop());
21         }
22     }
23     
24     /** Removes the element from in front of queue and returns that element. */
25     public int pop() {
26         return stack.pop();
27     }
28     
29     /** Get the front element. */
30     public int peek() {
31         return stack.peek();
32     }
33     
34     /** Returns whether the queue is empty. */
35     public boolean empty() {
36         return stack.isEmpty();
37     }
38 }

 

  方法二、

    使用两个 Stack,input、output。

    push: 压入 input 栈。

    pop、peek: 若 output 不为空,则对 output 操作; 若 output 为空,则将 input 元素全部压入 output,在对 output 操作。

    empty: 当 output、input 全为空时才返回 true。

 1 class MyQueue {
 2 
 3     Stack<Integer> input = new Stack<>();
 4     Stack<Integer> output = new Stack<>();
 5     
 6     public void push(int x) {
 7         input.push(x);
 8     }
 9     
10     public int pop() {
11         peek();
12         return output.pop();
13     }
14     
15     public int peek() {
16         if(output.isEmpty()) {
17             while(!input.isEmpty())
18                 output.push(input.pop());
19         }
20         return output.peek();
21     }
22     
23     public boolean empty() {
24         return input.empty() && output.empty();
25     }
26 }

 

    

转载于:https://www.cnblogs.com/skillking/p/9930483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值