資料結構——判斷迴文
阿新 • • 發佈:2019-02-05
#include<stdio.h> #include<stdlib.h> #define MAXCHAR 40 struct node{ char data; struct node * next; }; int ishs(struct node * head, int n) { char stack[MAXCHAR / 2]; struct node * p = head; int top = 0; while (top < n / 2)//將前半部分元素入棧 { stack[top] = p->data; top++; p = p->next; } if (n % 2 == 1) { p = p->next; } top--; for (int i = 0; i < n / 2; i++) { printf("%c,", stack[i]); } while (top >= 0 && p != NULL&&stack[top] == p->data) { top--; p = p->next; } if (top == -1&&p == NULL)//比較完畢,是迴文 return 1; else return 0; } int main() { char s[MAXCHAR]; struct node * head = NULL, *q, *p; int i = 0; printf("輸入一個數:"); scanf("%s", s); while (s[i] != '\0') { p = (struct node *)malloc(sizeof(struct node)); p->data = s[i]; p->next = NULL; if (head == NULL) { head = p; q = p; } else { q->next = p; q = p; } i++; } if (ishs(head, i)==1) printf("%s是迴文\n", s); else printf("%s不是迴文\n", s); system("pause"); return 0; }