#include <iostream>
#include <string.h>
using namespace std;
#define MAXSIZE 100
#define ERROR 0
#define OK 1
#define MAXSIZE 100
#define OVERFLOW -2
typedef int Status;
typedef char selemtype;
typedef struct{
selemtype *base;
selemtype *top;
int stacksize;
}SqStack;
//初始化
Status InitStack(SqStack &S)
{
S.base=new selemtype[MAXSIZE];
if(!S.base) return OVERFLOW;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
//入栈
Status Push(SqStack &S,selemtype e)
{
if(S.top-S.base==S.stacksize)
return ERROR;
*S.top++=e;
return OK;
}
//出栈
Status Pop(SqStack &S,selemtype &e)
{
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
bool StackEmpty(SqStack S)
{
if(S.top!=S.base)
return true;
else
return false;
}
int IsHuiWen(char *t)//将一半字符入栈,再弹出字符比较,
//int IsHuiWen(char t[]) //注意字符序列长度的奇偶性
{ int flag=0;
SqStack s;
selemtype e,temp;
InitStack(s);
int i,n;
n=strlen(t);
for(i=0;i<n/2;i++)//将一半字符入栈
{
Push(s,t[i]);
}
for(i=(n%2==0? n/2:(n+1)/2);i<n;i++)//判断n的奇偶性
{
Pop(s,e);
temp=e;
if(temp==t[i])
flag=1;
else
{
flag=0;
break;
}
}
return flag;
}
int main()
{
cout<<"请输入长度不大于100的字符序列:\n";
char str[MAXSIZE];
cin>>str;
if(IsHuiWen(str))
cout<<"此序列是回文数!\n";
else
cout<<"此序列不是回文数!\n";
return 0;
}
12:括号匹配
#include <stdio.h>
#include <stdlib.h>
#define Maxsize 100
typedef struct ST
{
char data[Maxsize];
int top;
}Stack;
void Init(Stack *L)
{
L->top=-1;
}
void Push(Stack *L,char x)
{
if(L->top>=Maxsize)
{
return;
}
L->top++;
L->data[L->top]=x;
}
int Empty(Stack L)
{
if(L.top==-1)
{
return 1;//为空返回1
}
return 0; //不为空返回0
}
void Print(Stack L)
{
for(int i=L.top;i>-1;i--)
{
printf("%c ",L.data[i]);
}
}
void Pop(Stack *L)
{
if(L->top==-1)
{
return;
}
L->top--;
}
char Get(Stack L)
{
return L.data[L.top];
}
int main()
{
Stack L;
char s[100];
while(gets(s))
{
Init(&L);
int flag=1;
//printf("%s",s);
for(int i=0;s[i]!='\0';i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
if(L.top<Maxsize)
{char x=s[i];
Push(&L,x);}
}
else if(s[i]==')')
{
if(Empty(L))
{flag=0;
break; }
else
{
if(Get(L)=='(')
{Pop(&L);}
else
{flag=0;
break;}
}
}
else if(s[i]=='}')
{
if(Empty(L))
{flag=0;
break;}
else
{
if(Get(L)=='{')
{Pop(&L);}
else
{flag=0;
break;}
}
}
else if(s[i]==']')
{
if(Empty(L))
{
flag=0;
break;
}
else
{
if(Get(L)=='[')
{Pop(&L);}
else
{flag=0;
break;}
}
}
}
if(!Empty(L))
{
flag=0;
}
if(flag==1&&Empty(L))
{printf("yes\n");}
else
{printf("no\n");}
}
return 0;
}