2012-06-07 78 views
0

我在大學被分配了這個練習,但我不知道如何實現遞歸結構(代碼中的「???」)。在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','\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; 
} 

回答

0
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; 
} 
+0

非常感謝! :) –

+1

作業==不給予免費的迴應... –

+0

@MichaelDorgan我不要求免費的迴應,我問的建議。 –

2

首先,您需要將值由指針,而不是指針本身比較指着

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指向恩迪ng '\0',它不會與任何其他字符匹配。

+0

非常感謝你,很好的解釋! –

+0

@ osiris_0100 - 更新了if(last Attila