weixin_58518282 2022-05-20 12:13 采纳率: 50%
浏览 102

帮我解释一下代码:C语言设计一个完整的算法,利用栈结构判以’@’为结束符的字母序列是否为“回文”。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define FULL 10000
#define MAX 10000
typedef struct elem {
char d;
struct elem *next;
}elem;

typedef struct stack { //定义栈
int cnt;
struct elem *top;
}stack;
void push(char d,struct stack *stk){
struct elem *p;
if (stk->cnt != FULL){
p = (struct elem *)malloc(sizeof(struct elem));
p->d = d;
p->next = stk->top;
stk->top = p;
stk->cnt++;
}
}

char pop(struct stack *stk){
char d;
struct elem *p;
if(stk->cnt != FULL){
d = stk->top->d;
p = stk->top;
stk->top = stk->top->next;
stk->cnt--;
free(p);
}
return d;
}

void initialize(struct stack *stk){
stk->cnt = 0;
stk->top = NULL;
}
main(){
char input[MAX];
struct stack temp;
int i = 0;
int flag = 0;
initialize(&temp);
printf("请输入字符(以‘@’为结束符)\n");
scanf("%s", &input); //输入字符串

while (input[i] != '@'){                //字符串入栈
    push(input[i],&temp);
    i++;
}

while (temp.cnt != 0){                    //字符依次出栈和字符数组比较,判断是否回文数
    if (temp.top->d == input[flag]){
        pop(&temp);                        //删除字符
        flag++;
    }
    else{
        printf("此字符序列不是回文序列!\n");
        break;
    }
}
if (temp.cnt == 0)
    printf("此字符序列是回文序列!\n");
return 1;

}

  • 写回答

1条回答 默认 最新

  • 张十五 2022-05-20 14:42
    关注

    回文吗,从头到尾读和从尾到头读是一样的。
    字符串入栈,是从头到尾,出栈就是从尾到头,栈的性质。
    出栈的时候,同时跟字符串,从头到尾比较,这不就是在验证回文串吗,有一个不相等,就不是回文

    评论

报告相同问题?

问题事件

  • 创建了问题 5月20日

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配