面试题9:用两个栈实现队列

这个题目需要注意,使用语言自带的stack函数实现,所以栈的大小是不用我们考虑的,但可以思考一下,加入需要我们自己实现栈,那么栈的大小就会是一个问题:当往stack1插入元素至stack1栈满时,这个时候怎么操作?

Java版本

package com.zr.test;

import java.util.Stack;

public class Num_9 {

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

	}
	
	public void push(int node) {
		stack1.push(node);
	}
	
	public int pop() {
		if(stack2.size() <= 0) {
			while(stack1.size() > 0) {
				stack2.push(stack1.peek());
				stack1.pop();
			}
		}
		if(stack2.size() == 0) {
			System.err.println("queue is empty.");
		}
		int head = stack2.peek();
		stack2.pop();
		return head;
	}

}

C++版本

#include <iostream>
#include <stack>
using namespace std;

stack<int> stack1;
stack<int> stack2;

void push(int node){
    stack1.push(node);
}

int pop(){
    if(stack2.size()<=0){
        while(stack1.size()>0){
            stack2.push(stack1.top());
            stack1.pop();
        }
    }
    if(stack2.size() == 0){
        cout<<"queue is empty."<<endl;
    }

    int head = stack2.top();
    stack2.pop();
    return head;
}

int main(){
    int a[5] = {1,2,3,4,5};
    cout<<&a[2]<<" "<<&a[3]<<endl;
    return 0;
}

原文地址:https://www.cnblogs.com/flyingrun/p/13299305.html