#数据结构与算法学习笔记#剑指Offer5:用两个栈实现队列(Java、C/C++)

234 篇文章 1 订阅
80 篇文章 0 订阅

2018.7.31     《剑指Offer》从零单刷个人笔记整理(66题全)目录传送门​​​​​​​

栈是后进先出,队列是先进先出,因此用两个栈正好可以模拟一个队列。每次进栈压入栈1,出栈时如果栈2没有元素,先从栈1弹出装入栈2,然后弹出栈2元素;如果栈2仍有元素,则依次弹出。


题目描述

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


JAVA实现:

/**
 * 
 * @author ChopinXBP
 * 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 *
 *
 */

import java.util.Stack;

public class TwoStack2Queue {
	
    static Stack<Integer> stack1 = new Stack<Integer>();
    static Stack<Integer> stack2 = new Stack<Integer>();
	
    public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

    public static void push(int node) {
        if(stack1.size() != stack1.capacity()){
        	stack1.push(node);
        }
    }
    
    public static int pop() {
    	//可换成isEmpty()
    	if(stack2.size() != 0){
    		return stack2.pop();
    	}else if(stack2.size() == 0 && stack1.size() != 0){
    		while(stack1.size() != 0){
    			stack2.push(stack1.pop());
    		}
    		return stack2.pop();
    	}
    	return -1;
    }
}

C++最佳解答示例:

class Solution
{
public:
    int cou = 0;
    void push(int node) {
        stack1.push_back(node);
        stack2.push_back(cou++);
    }
 
    int pop() {
        int i = 0;
        while(stack2[i] == -1)
            {
            i++;
        }
        stack2[i] = -1;
        return stack1[i];
    }
 
private:
    vector<int> stack1;//存数
    vector<int> stack2;//地址
};

#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值