回文指的是一个字符串从前面读和从后面读都一样,编写一个算法判断一个字符串是否为回文。

**回文指的是一个字符串从前面读和从后面读都一样,编写一个算法判断一个字符串是否为回文。
要求:
1)采用链栈实现算法;
2)从键盘输入一个字符串,输出判断结果。
**
*算法思路:
根据栈的后进先出的特点,编写一个回文判断算法,对出栈元素和原输入的元素依次比较,一旦发现有不相同的元素即证明不是回文,否则即是回文。
*

/*蓝多多 算法实验三:回文的判断  */
#include"stdio.h"
#include"stdlib.h"
#include <iostream>
using namespace std;
typedef char ElemType;
typedef struct stnode
{
    ElemType data;
    struct stnode* next;
}StNode;
int huiwen(char str[])
{
    int i = 0,j = 0;
    char ch;
    StNode* sl = NULL, * p;
    while ((ch = str[i++]) != '\0')
    {
        p = (StNode*)malloc(sizeof(StNode));
        p->data = ch;
        p->next = sl;
        sl = p;
    }
    while (sl != NULL)
    {
        p = sl;
        ch = p->data;
        sl = sl->next;
        free(p);
        if (ch != str[j++])
            return 0;
    }
    return 1;
}
void main()
{
    while (1) 
    {
        char string[20];
        int hw;
        printf("Please input a string:");
        gets_s(string);
        hw = huiwen(string);
        if (hw) { printf("The string is HUIWEN."); cout << endl; }
        else { printf("The string is not HUIWEN."); cout << endl; }
    }
}


猜你喜欢

转载自blog.csdn.net/qq_43554335/article/details/105577469