由两个栈组成队列

【说明】:

  本文是左程云老师所著的《程序员面试代码指南》第一章中“由两个栈组成的队列”这一题目的C++复现。

  本文只包含问题描述、C++代码的实现以及简单的思路,不包含解析说明,具体的问题解析请参考原书。

  感谢左程云老师的支持。

【题目】:

  编写一个类,用两个栈实现队列,支持队列的基本操作(push、pop、front)。

【思路】:

  一个栈作为数据的压如栈,一个栈作为数据的弹出栈。

【编译环境】:

  CentOS6.7(x86_64)

  gcc 4.4.7

【实现】:

  1、声明代码

/*
 *文件名:twoStaToQue.h
 *作者:
 *摘要:利用两个栈实现队列
 */
#ifndef _TWOSTATOQUE_H
#define _TWOSTATOQUE_H

#include<stack>
using namespace std;

class twoStaToQue
{
public:
    void push(int data);
    void pop();
    int front();
private:
    stack<int> spush;
    stack<int> spop;
};
#endif
View Code

  2、实现代码

/*
 *文件名:twoStaToQue.cpp
 *作者:
 *摘要:利用两个栈实现一个队列
 */

#include "twoStaToQue.h"
#include <stdexcept>
void twoStaToQue::push(int data)
{
    spush.push(data);
    return ;
}

void twoStaToQue::pop()
{
    if(spop.empty() && spush.empty())
        throw runtime_error("Empty Queue!");
    else if(spop.empty())
    {
        while(!spush.empty())
        {
            int tmp = spush.top();
            spop.push(tmp);
            spush.pop();
        }
    }
    spop.pop();
    return ;
}

int twoStaToQue::front()
{
    if(spop.empty() && spush.empty())
        throw runtime_error("Empty Queue!");
    else if(spop.empty())
    {
        while(!spush.empty())
        {
            int tmp = spush.top();
            spop.push(tmp);
            spush.pop();
        }
    }
    return spop.top();
}
View Code

  3、测试代码

/*
 *文件名:test.cpp
 *作者:
 *摘要:两个栈实现一个队列的测试代码
 */

#include "twoStaToQue.h"
#include <iostream>

int main()
{
    int a[]={3,4,5,1,2,1};
    twoStaToQue q;
    int i;
    for(i=0;i<3;i++)
    {
        q.push(a[i]);
    }
    cout << "q.front():" << q.front() <<endl;
    for(;i<6;i++)
    {
        q.push(a[i]);
    }
    for(i=0;i<6;i++)
    {
        cout << "q.front():" << q.front() <<endl;
        q.pop();
    }
    return 0;
}
View Code

注:

  转载请注明出处;

  转载请注明源思路来自于左程云老师的《程序员代码面试指南》。

原文地址:https://www.cnblogs.com/PrimeLife/p/5314204.html