栈,队列算法题

由两个栈实现队列

入队时,将元素压入s1。
出队时,判断s2是否为空,如不为空,则直接弹出顶元素;如为空,则将s1的元素逐个“倒入”s2,把最后一个元素弹出并出队。
这个思路,避免了反复“倒”栈,仅在需要时才“倒”一次。但在实际面试中很少有人说出,可能是时间较少的缘故吧。
http://www.cnblogs.com/wanghui9072229/archive/2011/11/22/2259391.html

由两个队列实现栈

转自:http://www.cnblogs.com/Trony/archive/2012/08/16/2642680.html
若用两个queue实现(可以定义成queue的数组queue q[2]),可以增加一个currentIndex来指向当前选中的queue。入栈操作可以直接把元素加到queue里,即 queue[currentIndex].push(element),时间复杂度为O(1),出栈操作要复杂一些,还是因为栈和队列元素的出入顺序不 同,处理方法是将size()-1个元素从q[currentIndex]转移到空闲队列q[(currentIndex + 1)%2]中,q[currentIndex]最后一个剩下的元素恰对应栈顶元素,之后更新一下currentIndex即可,时间复杂度为O(N);

#include "stdafx.h"
#include <iostream>
#include <queue>
#include <cassert>
using namespace std;

template <class T>
class YL_Stack
{
public:
    YL_Stack() :currentIndex(0)
    {

    }
    void push(const T &element); //入栈
    void pop();  //出栈
    T top();  //栈顶元素
    size_t size() const;  //栈的大小
    bool empty() const;   //判断栈是否为空


private:
    int currentIndex;
    queue<T> q[2];
};

template <class T>
void YL_Stack<T>::push(const T &element)
{
    q[currentIndex].push(element);
}

template <class T>
size_t YL_Stack<T>::size() const
{
    return q[0].size() + q[1].size();
}

template <class T>
bool YL_Stack<T>::empty() const
{
    return (size() == 0);
}

template <class T>
void YL_Stack<T>::pop()
{
    assert(!empty());

    int index = (currentIndex + 1) % 2;
    while (q[currentIndex].size()>1)
    {
        T temp = q[currentIndex].front();
        q[currentIndex].pop();
        q[index].push(temp);
    }

    q[currentIndex].pop();
    currentIndex = index;
}

template <class T>
T YL_Stack<T>::top()
{
    assert(!empty());

    int index = (currentIndex + 1) % 2;
    T temp;
    while (q[currentIndex].size()>0)
    {
        temp = q[currentIndex].front();
        q[currentIndex].pop();
        q[index].push(temp);
    }

    currentIndex = index;
    return temp;
}


void main()
{
    YL_Stack<int> myStack;
    myStack.push(1);
    myStack.push(2);
    myStack.push(3);
    myStack.push(4);
    myStack.push(5);
    cout << "1栈的大小为:" << myStack.size() << endl;
    cout << "1栈顶元素为:" << myStack.top() << endl;
    myStack.pop();
    myStack.pop();
    myStack.pop();
    cout << "2栈的大小为:" << myStack.size() << endl;
    cout << "2栈顶元素为:" << myStack.top() << endl;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值