编写算法,将十进制正整数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;
}