C++ 回文判断函数设计:顺序栈与循环队列实现
C++ 回文判断函数设计:顺序栈与循环队列实现
本文将使用 C++ 语言实现回文判断函数,并利用顺序栈和顺序循环队列两种数据结构,旨在展示数据结构在算法中的应用。代码将避免使用异或运算符,以提供更清晰的理解。
回文判断函数的设计
#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
// 使用顺序栈和顺序循环队列两种数据结构实现回文判断
bool isPalindrome(string str) {
stack<char> s;
queue<char> q;
int len = str.length();
for (int i = 0; i < len; i++) {
s.push(str[i]);
q.push(str[i]);
}
while (!s.empty() && !q.empty()) {
if (s.top() != q.front()) {
return false;
}
s.pop();
q.pop();
}
return true;
}
main 函数进行测试
int main() {
string str1 = 'racecar';
string str2 = 'hello';
cout << str1 << ' is palindrome? ' << isPalindrome(str1) << endl;
cout << str2 << ' is palindrome? ' << isPalindrome(str2) << endl;
return 0;
}
测试结果
racecar is palindrome? 1
hello is palindrome? 0
总结
本文通过 C++ 代码示例,展示了使用顺序栈和顺序循环队列实现回文判断函数的方法。该方法简单易懂,有效地利用了数据结构的特点,可以方便地扩展到其他字符串处理问题中。
原文地址: https://www.cveoy.top/t/topic/ntHy 著作权归作者所有。请勿转载和采集!