数据结构之栈的操作及应用(C++;进制转换;括号匹配)

#include<iostream>
#include<string.h>
using namespace std;

#define STACK_INIT_SIZE 100
#define TURE 1
#define FALSE 0
struct SqStack{
    int *base;
    int *top;
    int stacksize;
}; 
void DestroyStack(SqStack &s){
    delete s.base;
}
void push(SqStack &s,int e){
    *s.top++=e;
}
void pop(SqStack &s,int &e){
    e=*--s.top;
}
void InitStack(SqStack &s){
    s.stacksize=STACK_INIT_SIZE;
    s.base=new int[s.stacksize];
    s.top=s.base;
}
bool StackEmpty(SqStack &s){
    if(s.top==s.base)
        return TURE;
    else
        return FALSE;
}

/*
//使用栈将十进制转换为八进制 
int main(){
    int n,e;
    SqStack s;
    InitStack(s);
    cout<<"十进制:"<<endl; 
    cin>>n;
    cout<<"八进制:"<<endl;
    while(n){
        push(s,n%8);
        n/=8;
    }
    while(!StackEmpty(s)){
        pop(s,e);
        cout<<e;
    }
    DestroyStack(s);
}
*/


//使用栈判别括号是否配对 
int main(){
    char expr[STACK_INIT_SIZE];
    cin.getline(expr,STACK_INIT_SIZE);
    int i,j,length=strlen(expr);
    cout<<length<<endl;
    SqStack s;
    InitStack(s);
    for(i=0;i<length;i++){
        if(expr[i]=='(')
            push(s,i+1);
        else if(expr[i]==')'){
            if(!StackEmpty(s)){
                pop(s,j);
                cout<<"("<<j<<","<<i+1<<")"<<endl;
            }
            else
                cout<<"No match at "<<i+1<<endl;
        }
    }
    while(!StackEmpty(s)){
        pop(s,j);
        cout<<"No match at "<<j<<endl;
    }
    DestroyStack(s);
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值