(剑指Offer)面试题7:用两个栈实现队列

题目:

用两个栈实现一个队列。

队列的声明如下:请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。

思路:

根据栈的“先进后出”特点,如果将数据导入一个栈,再导入另一个栈,这样数据的出入顺序就变成了“先进先出”,即队列的特点。

假设有两个栈,stack1,stack2.

插入结点:直接压入stack1

删除结点:如果stack2为空,则将stack1中的结点导入stack2,;如果不为空,则从stack2弹出结点。

代码:

#include <iostream>
#include <stack>
#include <exception>

using namespace std;

template<typename T>
class CQueue{
public:
    CQueue();
    ~CQueue();

    void appendTail(const T& node);
    T deleteHead();
private:
    stack<T> stack1;
    stack<T> stack2;
};

template<typename T>
void CQueue<T>::appendTail(const T& element){
    stack1.push(element);
}

template<typename T>
T CQueue<T>::deleteHead(){
    if(stack2.size()<=0){
        while(stack1.size()>=0){
            T& data=stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }
//    if(stack2.size()==0)
//        throw new exception("queue is empty");

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

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

在线测试OJ:

http://www.nowcoder.com/books/coding-interviews/54275ddae22f475981afa2244dd448c6?rp=1

AC代码:

class Solution
{
public:
	void push(int node) {
		stack1.push(node);
	}

	int pop() {
		if(stack2.size()<=0){
            int data;
            while(stack1.size()>0){
                data=stack1.top();
                stack1.pop();
                stack2.push(data);
            }
        }
        if(stack2.size()<=0)
            return -1;
        int del=stack2.top();
        stack2.pop();
        return del;
	}

private:
	stack<int> stack1;
	stack<int> stack2;
};
原文地址:https://www.cnblogs.com/AndyJee/p/4627106.html