java栈和队列验证回文串_数据结构作业之栈和队列实现字符串回文数判断

字符串回文的判断是比较常见的问题,有各种方法来判断回文串。在数据结构中,利用栈和队列的特性也可以来实现回文判断。我们将字符串压入栈,然后在弹出,将弹出的元素压入队列,并出队进行判断。大概的思路就是这样,很久之前写的了,具体的实现思路都忘了,大概阐述下思路,在这里做个笔记,方便以后看看。下面我们来看看实现:

#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;

}

最后实现:

6bf69671c705cd04e61a4d7ac03088df.png

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值