作业帮 > 综合 > 作业

栈和队列判断回文怎样实现算法

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/30 03:19:59
栈和队列判断回文怎样实现算法
然后出栈并依次和字符数组比较是否相等,从而判断字符序列是否回文数,代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define EMPTY 0
#define FULL 10000
#define MAX 10000
typedef char data;
typedef struct elem {
data d;
struct elem *next;
}elem;
typedef struct stack {
int cnt;
elem *top;
}stack;
void initialize(stack *stk);
void push(data d,stack *stk);
data pop(stack *stk);
bool empty(const stack *stk);
bool full(const stack *stk); //栈操作函数
void initialize(stack *stk)
{
stk->cnt = 0;
stk->top = NULL;
}
bool empty(const stack *stk)
{
return stk->cnt == EMPTY;
}
bool full(const stack *stk)
{
return stk->cnt == FULL;
}
void push(data d,stack *stk)
{
elem *p;
if (!full(stk))
{
p = (elem *)malloc(sizeof(elem));
p->d = d;
p->next = stk->top;
stk->top = p;
stk->cnt++;
}
}
data pop(stack *stk)
{
data d;
elem *p;
if(!empty(stk))
{
d = stk->top->d;
p = stk->top;
stk->top = stk->top->next;
stk->cnt--;
free(p);
}
return d;
}
int main(void)
{
data input[MAX];
stack temp;
int i = 0;
int flag = 0;
initialize(&temp); //初始化临时栈
scanf("%s",&input); //输入字符串
while (input[i] != '@')
{//字符串入栈
push(input[i],&temp);
i++;
}
while (!empty(&temp))
{//字符依次出栈和字符数组比较,判断是否回文数
if (temp.top->d == input[flag])
{
pop(&temp);
flag++;
}
else
{
printf("此字符序列不是回文数!\n");
break;
}
}
if (empty(&temp))
printf("此字符序列是回文数!\n");
return 1;
}
运行结果: