leetcode 232两个栈模拟一个队列

36 篇文章 3 订阅
14 篇文章 1 订阅

原题:

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


题意:用两个栈实现一个队列,需要完成的方法有1 入队;2 出队;3 获取队头元素;4 判断队列是否为空。

思路其实蛮简单的。难点主要是在使用栈模拟入队出队的过程。栈的特点是后进先出,队列的特点是先进先出。我们借助两个栈,一个栈用于存储入队的元素(栈1),另一个栈用于出队操作(栈2)。出队的时候先判断栈2是否为空,如果为空,去栈1判断,说明前面一直在入栈,没有出栈的操作。这时候将栈1中的元素全部出栈,加到栈2中去。这时候,通过栈2的出栈操作,来模拟出队操作。

代码如下:

import java.util.*;
class MyQueue {

    /** Initialize your data structure here. */
    public MyQueue() {
        
    }
    Stack<Integer> stack1 =new Stack();
    Stack<Integer> stack2 =new Stack();//题目中要求了,队列中元素为int型
    /** Push element x to the back of queue. */
    public void push(int x) {
         stack1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (stack2.isEmpty()){
          while (!stack1.isEmpty()){
              stack2.push(stack1.pop());
          }
      }
        return stack2.pop();
        
    }
    
    /** Get the front element. */
    public int peek() {
          if (stack2.isEmpty()){
          while (!stack1.isEmpty()){
              stack2.push(stack1.pop());
          }
      }
        return stack2.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
       if(stack1.isEmpty()){
           return stack2.isEmpty();
       }
        if(stack2.isEmpty()){
            return stack1.isEmpty();
        }else{
            return false;
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值