简体   繁体   中英

Recursive function for the recognition of the palindrome char arrays

I been assigned this exercise at college, but I don't know how to implement the recursion structure ( " ??? " in the code ). In the if-cycle I should match the first character in the array with the last and apply the recursion in order to reach the central character, but I don't know how to setup the code. The main function code compiles perfectly.

#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','\0'};
    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;
}

First of all, you will need to compare the values pointed to by the pointers, not the pointers themselves

if (*first == *last)

Second, you can advance the first and decrease the last to move one character:

// inside if
++first;
--last;

and call the function again with the new values of the pointers:

return is_palindrome(first, last);

You will also need to ensure that you do not go past the array when you actually get a palindrome, so add this check to the beginning of is_palindrome()

if (last < first) {
  return true;
}

Also, in main() you need to initialize your pointers this way:

char* first = &a[0];
char* last = &[DIM-2];

The way you wrote it first already points past the array, while last points to the ending '\\0' , which will not match to any of the other characters.

using namespace std;

const int DIM = 8;

bool is_palindrome ( char* first , char* last )
{
    if ( *first == '\0' )
    {
        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','\0'};
    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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM