【剑指offer】用两个栈实现队列

题目链接

牛客网


题目描述

用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。

栈的特性:先进入的后出来,后进入的先出来(First in last out)
队列的特性:先进来的先出去(First in first out)

想要利用两个栈实现队列的特性,我们不难想到:一个栈用来 push,时间复杂度为 O(1),pop 的时候将栈中元素全部 pop 到第二个栈中。然后再将第二个栈中的元素全部 pop 回第一个栈。时间复杂度为O(n)

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        stack1.push(node);
    }
    
    public int pop() {
        if (stack1.isEmpty())
            throw new RuntimeException();
        while(!stack1.isEmpty()) {
            int e = stack1.pop();
            stack2.push(e);
        }
       
        int ret = stack2.pop();
        while(!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }

        return ret;
    }
}

我们发现,在pop()的时候,要两次将栈中所有元素出栈,未免有些麻烦。于是,我们想到,pop 的时候,我们先不急着将第二个栈中的元素全部 pop 回第一个栈,等到第二个栈为空之后,我们再将第一个栈中的元素全部pop到第二个栈

入栈 1, 2, 3

stack1

123

stack2


出栈 1

stack1

stack2

32

入栈 4, 5

stack1

45

stack2

32

出栈 2,3

stack1

45

stack2


出栈 4

stack1

stack2

5
import java.util.Stack;

public class Solution {
   Stack<Integer> stack1 = new Stack<Integer>();
   Stack<Integer> stack2 = new Stack<Integer>();
   
   public void push(int node) {
       stack1.push(node);
   }
   
   public int pop() {
       if (stack2.isEmpty()) {
           while (!stack1.isEmpty()) {
               stack2.push(stack1.pop());
           }
       }

       return stack2.pop();
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值