使用顺序栈写一个算法判定字符串是否为回文串C语言
时间: 2024-05-12 08:16:38 浏览: 77
好的,我可以帮您解答这个问题。以下是一个使用顺序栈判断字符串是否为回文串的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 50
typedef struct {
char data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *S) {
S->top = -1;
}
int StackEmpty(SqStack *S) {
if (S->top == -1)
return 1;
else
return 0;
}
int StackFull(SqStack *S) {
if (S->top == MAXSIZE - 1)
return 1;
else
return 0;
}
void Push(SqStack *S, char x) {
if (StackFull(S)) {
printf("Stack is full.\n");
exit(0);
} else {
S->data[++(S->top)] = x;
}
}
char Pop(SqStack *S) {
if (StackEmpty(S)) {
printf("Stack is empty.\n");
exit(0);
} else {
return S->data[(S->top)--];
}
}
int main() {
SqStack S;
char str[MAXSIZE], c;
int i, len, mid;
printf("请输入字符串:");
gets(str);
len = strlen(str);
mid = len / 2 - 1;
InitStack(&S);
for (i = 0; i <= mid; i++) {
Push(&S, str[i]);
}
if (len % 2 == 0) {
i = mid + 1;
} else {
i = mid + 2;
}
while (i <= len - 1) {
c = Pop(&S);
if (c != str[i]) {
printf("不是回文串!\n");
return 0;
}
i++;
}
printf("是回文串!\n");
return 0;
}
```
如果您有任何问题,欢迎继续提问!
阅读全文