C程式的迴文寫法(急~急~急~)

請問要怎麼"堆疊方式"以測試一個字串是否為迴文?

注意在迴文中我們會忽略空白字元,標點符號與字母大小寫。用下列的字串測試你的程式:

Go dog

Madam, I’m Adam

Madam, I’m not a palindrome

1 Answer

Rating
  • Anonymous
    1 decade ago
    Favorite Answer

    #include<stdio.h>

    #include <conio.h>

    #include <stdlib.h>

    #include <string.h>

    /* CONSTANT DECLARACTION

    */

    #define TRUE 1

    #define FALSE 0

    enum

    {

    IS_A_PALINDROME = 0,

    MEMORY_ALLOCATE_FAIL,

    NOT_A_PALINDROME,

    };

    /* DATA TYPE DECLARACTION

    */

    typedef int BOOL_T;

    typedef unsigned short UI16_T;

    typedef unsigned int UI32_T;

    /* LOCAL FUNCTIONS DECLARACTION

    */

    void main(void);

    static int Check_Palindrome (char *str);

    static void Check_Palindrome_And_Print(char *str);

    /* STATIC VARIABLES DECLARACTION

    */

    /* FUCTION BODY

    */

    static int Check_Palindrome (char *str)

    {

    /* local variables

    */

    int i, len;

    char *stack_base; /* base pointer of a stack */

    char *sp; /* stack pointer */

    char ch;

    /* body

    */

    len = strlen (str);

    if ( (sp = stack_base = malloc(len)) == 0 )

    return MEMORY_ALLOCATE_FAIL;

    /* remove the unexpected character and store it to a stack

    */

    for (i=0; i< len; i++)

    {

    ch = str[i];

    /* transfer 'little' letter to captital letter

    */

    if ( ch >= 'a' )

    ch += ('A'-'a');

    /* only accept letter & digit

    */

    if ( (ch >= '0' && ch <='9') ||

    ( ch >= 'A' && ch <= 'Z') )

    {

    *sp++ = ch; /* push stack and advance the sp */

    }

    } /* end of for */

    /* check IsaPalindrome

    */

    len = sp - stack_base;

    for (i=0; i< len/2; i++)

    {

    if ( stack_base[i] != stack_base[len-i-1])

    return NOT_A_PALINDROME;

    }

    return IS_A_PALINDROME;

    }

    static void Check_Palindrome_And_Print(char *str)

    {

    int st;

    st = Check_Palindrome (str);

    if ( st == IS_A_PALINDROME )

    printf( "\n\"%s\" is a Palindrome\n", str);

    else if ( st == MEMORY_ALLOCATE_FAIL )

    puts ( "Memory allocation fail");

    else

    printf( "\n\"%s\" is not a Palindrome\n", str);

    }

    2007-12-31 23:37:32 補充:

    void main (void)

    {

    Check_Palindrome_And_Print ("Go dog");

    Check_Palindrome_And_Print ("Madam, I’m Adam");

    Check_Palindrome_And_Print ("Madam, I’m not a palindrome");

    }

    Source(s): No
    • Login to reply the answers
Still have questions? Get your answers by asking now.