数据结构之顺序栈的实现与符号匹配和进制转换

#include <stdio.h>
#include <stdlib.h>
#define maxSize 100
//顺序栈 固定分配
typedef struct{
    int data[maxSize];
    int top;
}SqStack;

//初始化一个链表
void initStack(SqStack &stack)
{
    stack.top=-1;
}

int isEmpty(SqStack stack){
    if(stack.top==-1){
        printf("\r\nempty\r\n");
        return 1;
    }
    else return 0;

}
int stackLength(SqStack s){
    printf("len=%d ",++s.top);
    return ++s.top;

}
int isFull(SqStack stack){
    if(stack.top==maxSize-1)
        return 1;
    else return 0;

}
//出栈
void pop(SqStack &stack,int &e){
    if(stack.top==-1) return ;
     e = stack.data[stack.top];
     stack.top--;
  //     printf("  %d 出栈成功!\r\n",e);
}

//入栈
void push(SqStack &stack,int e){

    if(stack.top==maxSize-1) {
        printf("Full\r\n");
        return;     
    }
    stack.data[++stack.top] = e;
//  printf("  %d 入栈成功!\r\n",e);

}
int getTop(SqStack  stack){
    if(isEmpty(stack)==1) {
        exit(0);
    }

    printf("\r\nTop ele is %d \r\n",stack.data[stack.top]);
    return stack.data[stack.top];
}

void print(SqStack s){
    int i;
    int len = stackLength(s);
    printf("from bottom to top!\r\n");
    for(i=0;i<len-1;i++){
        printf("%d ",s.data[i]);
    }

}
int match(char arr[],int n){
    SqStack stack;
    initStack(stack);
    int i;
    for(i=0;i<n;i++){
        if(arr[i]=='('){
            stack.data[++stack.top] = '(';
            printf("%c is pushed!\r\n",'(');
        }
        if(arr[i]==')'){
            if(stack.top==-1){//右括号太多了....
                printf("match failed!\r\n");
                return 0;
            }else{
                printf("%c is matced!\r\n",'(');
                --stack.top;
            }
        }
    }
    if(stack.top==-1) printf("match successfully!\r\n");
    else{
        printf("match failed!\r\n");
        return 0;
    } 
}
//十进制的num转换为m进制的数 用stack完成
void convert(SqStack &stack,int num,int m){
    while(num){
        push(stack,num % m);
        num = num/m;
    }

    while(!isEmpty(stack)){
        int e = 0;
        pop(stack,e);
        printf("%d",e);
    }

}
int main(){
/*  char a1[4] = {'(','(',')',')'};//matched
    char a2[4] = {'(','(',')','('};
    match(a1,4);
    match(a2,4);
    SqStack s ;
    initStack(s);
    push(s,1);
    push(s,8);
    push(s,3);
    push(s,2);
    print(s);
    stackLength(s);
*/
    SqStack s ;
    initStack(s);
    int num = 8;
    int m = 2;
    convert(s,num,m);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值