回文指的是一個字符串從前面讀和從后面讀都一
樣,編寫一個算法判斷一個字符串是否為回文。
要求:
1)采用鏈棧實現算法;
2)從鍵盤輸入一個字符串,輸出判斷結果。
#include"stdio.h" #include"stdlib.h" typedef char ElemType; typedef struct stnode { ElemType data; struct stnode *next; }StNode, *LinkStack; int huiwen(char str[]) { int i = 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; } i = 0; while (sl != NULL) { p = sl; ch = p->data; sl = sl->next; free(p); if (ch != str[i++]) return 0; } return 1; } void main() { char string[20]; int hw; printf("input a string:"); gets_s(string); hw = huiwen(string); if (hw) printf("The string is HUIWEN."); else printf("The string is not HUIWEN."); }
歡迎訪問我的博客https://www.ndmiao.cn/