用于识别回文字符数组的递归函数
Recursive function for the recognition of the palindrome char arrays
我在大学里被分配了这个练习,但我不知道如何实现递归结构(代码中的"???")。 在 if 循环中,我应该将数组中的第一个字符与最后一个字符匹配并应用递归以到达中心字符,但我不知道如何设置代码。主函数代码完美编译。
#include <iostream>
using namespace std;
const int DIM = 8;
bool is_palindrome (char* first, char* last)
{
if (first == last)
{
???
}
else
return false;
}
int main()
{
char a[DIM] = {'i','n','g','e','g','n','i',' '};
char *first = &a[DIM] + 1;
char *last = &a[DIM] -1;
if (is_palindrome(first, last))
cout << " the char array is palindrome ";
else
cout << " the char array is not palindrome ";
return 0;
}
首先,您需要比较指针指向的值,而不是指针本身
if (*first == *last)
其次,您可以前进第一个并减少最后一个字符以移动一个字符:
// inside if
++first;
--last;
并使用指针的新值再次调用该函数:
return is_palindrome(first, last);
您还需要确保在实际获得回文时不会越过数组,因此将此检查添加到is_palindrome()
if (last < first) {
return true;
}
此外,在main()
中,您需要以这种方式初始化指针:
char* first = &a[0];
char* last = &[DIM-2];
您编写它的方式first
已经指向数组,而last
指向结尾' '
,这将与任何其他字符不匹配。
using namespace std;
const int DIM = 8;
bool is_palindrome ( char* first , char* last )
{
if ( *first == ' ' )
{
return false;
}
else if ( first >= last )
{
return true;
}
else if ( *first == *last )
{
return is_palindrome(first + 1, last - 1);
}
else
{
return false;
}
}
int main ()
{
char a[DIM] = {'i','n','g','e','g','n','i',' '};
char *first = a;
char *last = &a[DIM] - 2;
if ( is_palindrome ( first , last ) )
{
cout << " the char array is palindrome ";
}
else
{
cout << " the char array is not palindrome ";
}
return 0;
}
相关文章:
- 使用递归的数组的最小值.这是怎么回事
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 使用递归输出数组
- 将数组传递给递归函数,同时C++修改它
- 尝试递归获取数组元素的总和
- 如何使用递归函数返回数组中整数的索引?
- 在递归函数中更有效地创建对象和对象数组?C++
- 线性递归反转数组
- C 递归找到数组的最小值
- 递归反转数组
- 如何在递归函数中调用引用数组?
- 递归定义数组中的数据对齐和排序
- C++递归函数,使用高和低查找数组中的最小值
- 将动态数组作为副本传递给递归函数 C++
- 使用递归输出数组
- 使用递归查找数组中的最大相对值
- 使用递归 C++ 返回数组的子集
- 使用递归将数组中的元素相乘
- 使用递归查找数组中的第k个最小元素
- 使用递归计算数组中某个元素出现的次数