9.21日数据结构练习题

发布时间 2023-09-21 21:32:35作者: 新晋软工小白

用栈操作去判断一个字符串是不是回文数列

 1 #include <iostream>
 2 #define MAXSIZE 100
 3 using namespace std;
 4 //定义一个栈的结构体
 5 //包含顶指针,尾指针,长度 
 6 typedef struct{
 7     char* base;
 8     char* top;
 9     int stacksize;
10 }SqStack;
11 //创建一个空栈 
12 void InitStack(SqStack &S){
13     S.base=new char[MAXSIZE];
14     if(!S.base){
15         return;
16     }
17     S.top=S.base;
18     S.stacksize=MAXSIZE;
19     return;
20 }
21 //入栈函数 
22 void Push(SqStack &s,char e){
23     if(s.top-s.base==s.stacksize){
24         return;
25     }
26     *s.top++=e;
27     return;
28 }
29 //出栈函数 
30 void Pop(SqStack &s,char &e){
31     if(s.top==s.base){
32         return;
33     }
34     e=*--s.top;
35     return;
36 }
37 //判断是否为回文的函数 
38 void determinet(char s[],int n){
39     for(int i=0;i<n;i++){
40         if(s[i]==' '){
41             cout<<"入栈不成功"<<endl;
42             return;
43         }
44     }
45     SqStack S;
46     InitStack(S);
47     for(int i=0;i<n;i++){
48         Push(S,s[i]);
49     }
50     for(int i=0;i<n;i++){
51         char e;
52         Pop(S,e);
53         char c=e;
54         if(c!=s[i]){
55             cout<<"此字符串不是回文串"<<endl;
56             return;
57         }
58     }
59     cout<<"此字符串是回文串"<<endl;
60 }
61 int main(){
62     int n;
63     while(1){
64         cin>>n;
65         if(n<=100){
66             break;
67         }
68     }
69     getchar();
70     char s[n]; 
71     cin.getline(s,n); 
72     determinet(s,n);
73 }