栈
1.判断字符串对称性
#include<iostream>
#include <stdlib.h>
using namespace std;
typedef char ElemType;//字符型
#define MaxSize 20
//判断字符串是否对称
int Symmetry(ElemType *ch)
{
int i;
ElemType e;
SqStack *S;
InitStack(S);
for(i=0;str[i]!='\0';i++)
Push(S,ch[i]);
for(i=0;ch[i]!='\0';i++)
{
Pop(S,e);
// 判断字符串与逆序字符的关系
if(ch[i] != e )
return 0;
}
return 1;
free(S); //释放栈
}
int main()
{
char ch[MaxSize];
cout <<"请输入需要判断的字符串"<<endl;
cin >> ch;
cout << ch << endl;
int a = Symmetry(ch);
if(a == 0)
cout << "非对称字符"<<endl;
else if(a == 1)
cout << "对称字符"<<endl;
return 0;
}
2.用栈实现数制转换
将一个非负的十进制整数转换为其他进制数,利用栈实现。采用除基数取余的方法。
#include<iostream>
#include <stdlib.h>
using namespace std;
typedef int ElemType;
#define MaxSize 20
//以十进制数和基数作为参数
void Conversion(int n,int base)
{
SqStack*S;
ElemType bit=0;
InitStack(S);
while(n != 0)
{
Push(S,n%base);//余数入栈
n=n/base;//除数为n,被除数为基数
}
while(!Empty(S))
{
Pop(S,bit);
if(bit > 9)
printf("%c",bit+55);//A,B,C,D,E
else
printf("%c",bit+48);//0,1,2,3,4,5,6,7,8,9
}
}
int main()
{
int ch,n;
cout <<"请输入需要转换的10进制数"<<endl;
cin>>ch;
cout <<"输入要转换的进制"<<endl;
cin >> n;
cout<<n<<"进制数为: ";
Conversion(ch,n) ;
return 0;
}
- 支撑函数
//定义栈格式
typedef struct SqStack{
ElemType data[MaxSize];
int Top;
}SqStack;
//构造一个空栈
void InitStack(SqStack *& S)
{
S = (SqStack*)malloc(sizeof(SqStack));
S->Top = 0;
}
//判断栈空
int Empty(SqStack*S)
{
if(S->Top<=0) return 1;
else return 0;
}
int Push(SqStack *S,ElemType e)
{
if(S->Top >= MaxSize-1)
{
printf("栈上溢");
return 0;
}
else
{
S->data[++ S->Top] = e;
return 1;
}
}
//出栈
int Pop(SqStack *S,ElemType& e)
{
if (S->Top == 0)
{
return 0;
}
else
{
e = S->data[S->Top--];
return 1;
}
}