判断一个字符串是否为回文,如"abcda"不是回文,”abcba“是回文。
这道题目非常简单,有许多种方法可以求解。在这里,特别使用堆栈和队列共同来解决这个问题。
代码清单:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 20
typedef struct _stack{
char data[MAXSIZE];
int top;
} stack;
typedef struct _queue{
char data[MAXSIZE];
int front;
int rear;
} queue;
int isempty_queue(queue * xy)
{
return xy->front == xy->rear;
}
int isfull_queue(queue *xy)
{
return xy->rear >= MAXSIZE -1 ;
}
queue * init_queue(void)
{
queue * tmp = (queue*) malloc( sizeof(queue) );
tmp->front = tmp->rear = 0;
return tmp;
}
char dequeue(queue * xy)
{
if( isempty_queue(xy) )
{
printf("The queue is empty, cannon dequeue.\n");
exit(-5);
}
return xy->data[xy->front++];
}
void inqueue(queue *xy, char value)
{
if( isfull_queue(xy) )
{
printf("The queue is full, cannnot enqueue.\n");
exit(-6);
}
xy->data[xy->rear++] = value;
}
stack * init_stack(void)
{
stack * tmp = (stack *) malloc( sizeof(stack) );
tmp->top = 0;
return tmp;
}
int isempty_stack(stack *xy)
{
return xy->top == 0 ? 1 : 0;
}
int isfull_stack(stack *xy)
{
return xy->top >= MAXSIZE -1 ? 1: 0;
}
char pop(stack *xy)
{
if( isempty_stack(xy) )
{
printf("cannot pop, the stack is empty.\n");
exit(-2);
}
return xy->data[--xy->top];
}
void push(stack *xy, char value)
{
if( isfull_stack(xy) )
{
printf("cannot push, the stack is full.\n");
exit(-3);
}
xy->data[xy->top++] = value;
}
void judge(stack * a, queue *b, char str[], int len)
{
int i;
int flag = 0;
char temp_stack;
char temp_queue;
for(i = 0; i < len; i++)
{
push(a, str[i]);
inqueue(b, str[i]);
}
for(i = 0; i < len; i++)
{
temp_stack = pop(a);
temp_queue = dequeue(b);
if(temp_stack != temp_queue)
{
printf("Not Palindrome.\n");
flag = 1;
break;
}
}
if( !flag )
{
printf("The string is Palindrome.\n");
}
}
int main()
{
queue * stq = init_queue();
stack * stk = init_stack();
char c[MAXSIZE];
char *cc;
cc = fgets(c, MAXSIZE, stdin);
int len = strlen(c) - 1;
judge(stk, stq, c, len);
return 0;
}