【发布时间】:2020-12-19 00:50:22
【问题描述】:
在最近的一次编码面试中,我被要求解决一个问题,其中任务是完成一个函数,该函数通过引用接收堆栈作为参数,并检查传递的堆栈是否为回文。我确实想出了一个方法,但在我看来这根本不是一个好方法。
我的代码
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void copy_it(stack<int> &st, stack<int> &temp) {
if(st.empty())
return;
int element = st.top();
temp.push(element);
st.pop();
copy_it(st, temp);
st.push(element);
}
bool check_palindrome(stack<int> &st, stack<int> &temp) {
if(st.size() != temp.size())
return false;
while(!st.empty()) {
if(st.top() != temp.top())
return false;
st.pop();
temp.pop();
}
return true;
}
int main()
{
vector<int>vec{-1, -2, -3, -3, -2, -1};
stack<int>st;
for(int i = vec.size() - 1; i >= 0; --i) {
st.push(vec[i]);
}
stack<int> temp;
copy_it(st, temp);
cout << check_palindrome(st, temp);
return 0;
}
有没有更好的方法来做到这一点?我最好寻找递归算法/代码。
【问题讨论】:
标签: c++ algorithm stack palindrome stdstack