实现顺序栈的定义,头文件命名”sqstack.h°”。利用所定义的顺序栈,设计一个算法实现一个字符串是否对称的判断。
时间: 2024-05-14 16:14:37 浏览: 13
sqstack.h文件内容如下:
```c
#ifndef SQSTACK_H
#define SQSTACK_H
#define MAXSIZE 100 // 定义栈的最大长度
typedef struct{
char data[MAXSIZE]; // 存放栈中元素
int top; // 栈顶指针,即栈中元素个数
}SqStack;
// 初始化栈
void InitStack(SqStack *S);
// 判断栈是否为空
int StackEmpty(SqStack S);
// 进栈
int Push(SqStack *S, char x);
// 出栈
int Pop(SqStack *S, char *x);
#endif
```
对称判断算法实现如下:
```c
#include <stdio.h>
#include <string.h>
#include "sqstack.h"
int main(){
char str[MAXSIZE];
printf("请输入一个字符串:");
scanf("%s", str);
SqStack S;
InitStack(&S); // 初始化栈
int len = strlen(str);
int i;
for(i = 0; i < len/2; i++){ // 前一半字符依次进栈
Push(&S, str[i]);
}
if(len % 2 == 1){ // 若字符串长度为奇数,则中间字符不参与判断
i++;
}
char x;
while(i < len && !StackEmpty(S)){ // 后一半字符依次出栈并比较
Pop(&S, &x);
if(x != str[i]){
printf("该字符串不对称\n");
return 0;
}
i++;
}
if(StackEmpty(S)){ // 栈为空说明字符串对称
printf("该字符串对称\n");
}else{
printf("该字符串不对称\n");
}
return 0;
}
void InitStack(SqStack *S){
S->top = 0;
}
int StackEmpty(SqStack S){
return S.top == 0;
}
int Push(SqStack *S, char x){
if(S->top == MAXSIZE){ // 栈满
return 0;
}
S->data[S->top++] = x; // 将元素x入栈
return 1;
}
int Pop(SqStack *S, char *x){
if(S->top == 0){ // 栈空
return 0;
}
*x = S->data[--S->top]; // 将栈顶元素出栈
return 1;
}
```