编写判断一个字符序列是否为回文。回文是指一个字符序列以中间 字符为基准两边字符完全相同,即顺着看和倒着看是相同的字符序列。

来源:互联网 发布:js弹出警告窗口 编辑:程序博客网 时间:2024/05/29 10:25

头文件:函数的声明

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <malloc.h>typedef char ElemType;//链式堆栈结点类型定义typedef struct snode{ElemType data;struct snode *next;}LSNode;//只有队尾指针的链式循环队列类型定义typedef struct QNode{ElemType data;struct QNode *next;}LQNode,*LinkQueue;void InitStack(LSNode **head);int StackEmpty(LSNode *head);int PushStack(LSNode *head,ElemType e);int PopStack(LSNode *head,ElemType *e);void InitQueue(LinkQueue *rear);int QueueEmpty(LinkQueue rear);int EnQueue(LinkQueue *rear,ElemType e);int DeQueue(LinkQueue *rear,ElemType *e);


函数的定义

#include "链式队列.h"void InitStack(LSNode **head){if((*head = (LSNode*)malloc(sizeof(LSNode))) == NULL){printf("分配结点不成功!");exit(-1);}else{(*head)->next = NULL; }}int StackEmpty(LSNode *head){if(head->next == NULL){return 1;}else{return 0;}}int PushStack(LSNode *head,ElemType e){LSNode *s;if((s = (LSNode*)malloc(sizeof(LSNode))) == NULL){return 0;}else{s->data = e;s->next = head->next ;head->next = s;return 1;}}int PopStack(LSNode *head,ElemType *e){LSNode *s = head->next ;if(StackEmpty(head)){return 0;}else{head->next = s->next ;*e = s->data ;free(s);return 1;}}void InitQueue(LinkQueue *rear){if((*rear = (LQNode*)malloc(sizeof(LQNode))) == NULL){exit(-1);}else{(*rear)->next = *rear;}}int QueueEmpty(LinkQueue rear){if(rear->next = rear){return 1;}else{return 0;}}int EnQueue(LinkQueue *rear,ElemType e){LQNode *s;s = (LQNode*)malloc(sizeof(LQNode));if(!s){return 0;}else{s->data = e;s->next = (*rear)->next ;(*rear)->next = s;*rear = s;return 1;}}int DeQueue(LinkQueue *rear,ElemType *e){LQNode *f,*p;if(*rear == (*rear)->next){return 0;}else{f = (*rear)->next;p = f->next;if(p == *rear){*rear = (*rear)->next ;(*rear)->next = *rear;}else{f->next = p->next;}*e = p->data;free(p);return 1;}}


函数的应用

#include "链式队列.h"/*编写判断一个字符序列是否为回文。回文是指一个字符序列以中间字符为基准两边字符完全相同,即顺着看和倒着看是相同的字符序列。*/int main(void){LinkQueue LQueue1,LQueue2;LSNode *LStack1,*LStack2;char str1[] = "ABCDCBA";char str2[] = "ABCBCAB";char q1,q2,s1,s2;int i;InitStack(&LStack1);InitStack(&LStack2);InitQueue(&LQueue1);InitQueue(&LQueue2);for(i = 0;i < strlen(str1);i++){EnQueue(&LQueue1,str1[i]);PushStack(LStack1,str1[i]);}for(i = 0;i < strlen(str2);i++){EnQueue(&LQueue2,str2[i]);PushStack(LStack2,str2[i]);}printf("字符序列1:\n");printf("出队序列  出栈序列\n");while(!StackEmpty(LStack1)){DeQueue(&LQueue1,&q1);PopStack(LStack1,&s1);printf("%5c",q1);printf("%10c\n",s1);if(q1 != s1){printf("字符序列1不是回文!");return 0;}}printf("字符序列1是回文!\n");printf("字符序列2:\n");printf("出队序列  出栈序列\n");while(!StackEmpty(LStack2)){DeQueue(&LQueue2,&q2);PopStack(LStack2,&s2);printf("%5c",q2);printf("%10c\n",s2);if(q2 != s2){printf("字符序列2不是回文!");return 0;}}printf("字符序列2是回文!\n");return 0;}


0 0