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

2018.7.31

注意出栈之前若栈1仍有元素,需要把栈1的元素先全部压入栈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一秒钟。留个言点个赞呗,谢谢你#

猜你喜欢

转载自blog.csdn.net/qq_20304723/article/details/81296974