数据结构之栈的操作及应用(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);
}

猜你喜欢

转载自blog.csdn.net/muhehhh/article/details/81275988