剑指Offer——用两个栈实现队列

题目一:用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

利用两个栈s1和s2模拟一个队列。当需要向队列中插入一个元素,用s1来存放已输入的元素,即s1执行入栈操作。当需要出队的时候,需要对s2进行出栈的操作。由于从栈中取出的元素的顺序是逆序,所以必须将s1中的所有元素全部出栈并入栈到s2中,再在s2中执行出栈操作,即可实现出队列操作,而在执行此操作之前必须判断s2是否为空。

public class StackToQueue {
    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()){
            return stack2.pop();
        }
       while (!stack1.isEmpty())
       {
           int temp=stack1.pop();
           stack2.push(temp);
       }
       return stack2.pop();
    }
}

题目二:使用两个队列实现一个栈

压入:就是简单的直接压入一个队列中

弹出(或者取出栈顶元素):可以先从输入队列中依次删除元素并插入队列2中,再从输入队列中删除最后一个元素,这就相当于从栈中弹出元素。然后再把这个队列2中的元素再放回队列(输入队列中),就这样相互交换。

import java.util.Queue;
import java.util.LinkedList;
class MyStack {
    private Queue<Integer> q1; //输入队列
    private Queue<Integer> q2; //输出队列
    private Integer top;
    /** Initialize your data structure here. */
    public MyStack() {
        q1=new LinkedList<>();
        q2=new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q1.add(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    //移除栈顶元素
    public int pop() {
        while(q1.size()>1){
            int temp=q1.poll();
            q2.add(temp);
        }
        int value=q1.poll();
         while(q2.size()>0){
             q1.add(q2.poll());
         }
        return value;
    }
    
    /** Get the top element. */
    public int top() {
     while(q1.size()>1){
            int temp=q1.poll();
            q2.add(temp);
        }
        int value=q1.poll();
        q2.add(value);
        while(q2.size()>0){
             q1.add(q2.poll());
         }
        return value;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q1.isEmpty();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值