栈的实现基于上篇的链式栈。
10进制转8进制:
void conversion()
{
Stack S;
InitStack(S);
unsigned n;//非负整数
ElemType e;
cin>>n;
while(n)
{
Push(S,n%8);
n = n/8;
}
while(!StackEmpty(S))
{
Pop(S,e);
cout<<e;
}
cout<<endl;
}
10进制转16进制:
void conversion16()
{
Stack S;
InitStack(S);
unsigned n;//非负整数
ElemType e;
cin>>n;
while(n)
{
Push(S,n%16);
n = n/16;
}
while(!StackEmpty(S))
{
Pop(S,e);
if(e<=9)
{
cout<<e;
}else
{
cout<<(char)(e+55);
}
}
cout<<endl;
}
括号匹配检测:
//----------------括号匹配算法------------------------------
void check()
{
Stack S;
ElemType ch[80],*p,e;
if(InitStack(S))
{
cout<<"输入括号表达式"<<endl;
gets(ch);
p = ch;
while(*p)
{
switch (*p)
{
case '(':
case '[':
Push(S,*p++);//左括号入栈
break;
case ')':
case ']':
if(!StackEmpty(S))//栈非空
{
Pop(S,e);//出栈
if(e=='('&&*p!=')' || e=='['&&*p!=']')//不匹配
{
cout<<"括号不匹配"<<endl;
exit(ERROR);
}else//匹配
{
p++;
break;
}
}else//栈空
{
cout<<"缺少左括号"<<endl;
exit(ERROR);
}
default:
p++;
break;
}
}
if(StackEmpty(S))//栈空
{
cout<<"括号匹配!"<<endl;
}else//栈非空
{
cout<<"缺少右括号"<<endl;
}
}
}