假设称正读和反读都相同的字符序列为“回文”,例如’abba’和’abcba’是回文,’abcde’’ababab’则不是回文,试编写算法判别读入的一个以“@”为结束符的字符序列是否为“回文”。
由于依次输入的字符序列中不含特殊的分隔符,则在判别是否是回文时,可以同时利用栈和队列两种结构来实现。
#include<stdio.h>
#include<malloc.h>
//顺序栈的函数声明
typedef struct Qnode
{
char letter;
struct Qnode *next;
}Qnode;
typedef struct LinkQueue
{
struct Qnode *front;
struct Qnode *rear;
}LinkQueue;
typedef struct
{
char *word;
int top;
int size;
} Stack;
Stack* Create_Stack()
{
Stack *p;
p=(Stack *)malloc(sizeof(Stack));
if(!p){printf("栈内存分配失败\n");return 0;}
p->word=(char *)malloc(100*sizeof(char));
if(!p->word){printf("栈数据域内存分配失败\n");return 0;}
p->top=0;
p->size=100;
return p;
}
void Push(Stack *p,char letter)
{
if(p->top>=p->size){p->word=(char *)realloc(p->word,p->size+20*sizeof(char));p->size+=20;}
if(!p->word){printf("栈溢出,重新分配内存失败\n");return;}
p->word[p->top]=letter;
p->top++;
}
char Pop(Stack *p)
{
if(p->top==0){printf("栈此时为空\n");return 0;}
p->top--;
char ch=p->word[p->top];
p->word[p->top]=NULL;
return ch;
}
bool Empty_Stack(Stack *p)
{
if(p->top==0)return true;
else return false;
}
//链队列的函数声明
LinkQueue* Create_LinkQueue()
{
LinkQueue *linkQueue = (LinkQueue *)malloc(sizeof(LinkQueue));
if(!linkQueue){printf("申请内存失败\n");return 0;}
Qnode *qnode = (Qnode *)malloc(sizeof(Qnode));
if(!qnode){printf("申请内存失败\n");return 0;}
linkQueue->front=qnode;linkQueue->rear=qnode;
linkQueue->front->next=NULL;
return linkQueue;
}
void EnQueue(LinkQueue *linkQueue,char ch)
{
Qnode *qnode = (Qnode *)malloc(sizeof(Qnode));
if(!qnode) {printf("申请内存失败\n");return;}
qnode->letter=ch;
qnode->next=NULL;
linkQueue->rear->next=qnode;
linkQueue->rear=linkQueue->rear->next;
}
char DeQueue(LinkQueue *linkQueue)
{
char ch;
if(linkQueue->front==linkQueue->rear){printf("链队列为空\n");return 0;}
Qnode *qnode_del=linkQueue->front->next;
ch = qnode_del->letter;
linkQueue->front->next=qnode_del->next;
if(linkQueue->rear==qnode_del)linkQueue->rear=linkQueue->front;
free(qnode_del);
return ch;
}
void main()
{
char c;
bool isPalindrome=true;
Stack *stack1=Create_Stack();
LinkQueue *linkQueue1=Create_LinkQueue();
while((c=getchar())!='@')
{
Push(stack1,c);
EnQueue(linkQueue1,c);
}
while(!Empty_Stack(stack1))
{
if(Pop(stack1)!=DeQueue(linkQueue1))
isPalindrome=false;
}
printf("%s",isPalindrome? "是回文": "不是回文");
}