栈的基本操作-进制转换-括号配对

编写算法,将十进制正整数m转换成n(2≤n≤9)进制数 要求:1、验证输入m=10,n=2 2、将主要代码及运行结果截图上传  

括号匹配:利用栈的结构对输入的一组括号进行匹配

 要求 :1、测试如下样例:

               1.    [()[]{}]  匹配

               2.    (()[]   不匹配

               3.    (){}}   不匹配

           2、将主要代码及运行结果截图上传

代码:

/* 
1.新建顺序栈
2.依次将1,2,3,4,5压入栈中 
3.将栈中元素依次出栈并打印 
*/ 
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MaxSize  100
typedef  char ElementType;
typedef struct {
    ElementType data[MaxSize];
    int top;
} SqStack;

//新建栈 
SqStack * CreateStack( )
{   SqStack *s;
    s=(SqStack*)malloc(sizeof(SqStack));
    s->top=-1;
    return s; 
}

//判断栈是否为满,是返回1,否返回0 
int IsFull(SqStack  *s)
{    
    if(s->top==MaxSize-1)
        return 1;
    else
        return 0;
}

//判断栈是否为空,是返回1,否返回0 
int IsEmpty(SqStack * s)
{
    if(s->top==-1)
        return 1;
    else
        return 0;    
}

//压栈操作 
void Push( SqStack *s, ElementType x)
{  
     if(IsFull(s)==0)
         s->data[++s->top]=x; 
}

//出栈操作 
ElementType Pop( SqStack *s)
{
     if(IsEmpty(s)==0)
     return s->data[s->top--];  
}
 
void transform(int m,int n){
    SqStack *s=CreateStack();
    int num=m,yu;
    while(m){
        yu=m%n;
        Push(s,yu);
        m/=n; 
    }
    printf("将十进制正整数%d转换成%d进制数:\n",num,n); 
    while(IsEmpty(s)==0){
        printf("%2d",Pop(s));
    }
    
        
}
int check(char str[]){
    SqStack *s=CreateStack();
    int i=0;char pop_element;
    while(str[i]!='\0'){
        if(str[i]=='('||str[i]=='['||str[i]=='{'){
            Push(s,str[i]); 
        }
        else{
            if(IsEmpty(s))
                return 0;
            pop_element=Pop(s);
            if(str[i]==')'&&pop_element!='(')
                return 0;
            if(str[i]=='}'&&pop_element!='{')
                return 0;
            if(str[i]==']'&&pop_element!='[')
                return 0;        
        }
        i++;
    }
    return IsEmpty(s);
}
//[()[]{}] (()[] (){}}
int main()
{
    /*---------------1、新建栈--------------------------*/
//   SqStack * s=CreateStack();
//   /*---------------2、依次将1,2,3,4,5压入栈中 --------------------------*/
//   for(int i=1;i<=5;i++){
//        Push(s,i);
//   }
//   /*---------------3、将栈中元素依次出栈并打印  --------------------------*/
//    while(IsEmpty(s)==0){
//        printf("%4d",Pop(s));
//    }
//    transform(10,2);
    char s[MaxSize];
    while(1){
     scanf("%s",s);
    if(check(s))
         printf("匹配\n");
     else
         printf("不匹配\n");        
    }
     

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值