字符串回文的判断是比较常见的问题,有各种方法来判断回文串。在数据结构中,利用栈和队列的特性也可以来实现回文判断。我们将字符串压入栈,然后在弹出,将弹出的元素压入队列,并出队进行判断。大概的思路就是这样,很久之前写的了,具体的实现思路都忘了,大概阐述下思路,在这里做个笔记,方便以后看看。下面我们来看看实现:
#include
#include
#include
#include "windows.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);
system("pause");
return 0;
}
最后实现: