首页 > 解决方案 > 如何在 C++ 中编写一个递归函数模板来检查作为参数提供的两个堆栈是否相同?

问题描述

我必须为我正在做的模块完成一个函数模板,问题如下:
编写一个递归函数模板,相同的,检查作为参数提供的两个堆栈是否相同。如果是这种情况,该函数应返回布尔值 true,否则应返回布尔值 false。使用以下标头:
template
bool sameS (stackType S1, stackType S2);

下面是我没有测试过的代码,但我问你它是否可以工作,如果不行,你将如何纠正它:

template <class Type>
bool identicalS (stackType<Type> S1, stackType<Type> S2);


template <class Type>
bool identicalS (stackType<Type> S1, stackType<Type> S2)
{
    Type lh, rh;
    int ret = 0;

    if ( (lh = s1.pop()) == (rh = s2.pop()) ) {
        if ( !s1.isEmptyStack() and !s2.isEmptyStack() ) return identicalS(s1, s2);
        else ret = 1;
    }
    s1.push(lh);
    s2.push(rh);

    return ret;
}

标签: c++

解决方案


推荐阅读