c语言数据结构题目求大神答案 50
1、编制程序,从键盘接收一个字符表达式(长度最长为100),检测其中的括号(),[],{}是否匹配情况,如果匹配,输出匹配的括号对数。提示:(1)设置一个括号顺序栈s_b...
1、编制程序,从键盘接收一个字符表达式(长度最长为100),检测其中的括号(),[],{}是否匹配情况,如果匹配,输出匹配的括号对数。
提示:(1)设置一个括号顺序栈s_bracket(字符数组data[]存放字符表达式中的括号,整型变量top作为栈顶指针);
typedef struct stack
{
char data[MaxSize];
int top;
}s_bracket;
(2)用字符数组exps[MaxSize]存放表达式;
(3)下标i扫描表达式字符数组exps[MaxSize],忽略非括号字符,
①遇到左括号“(”、“[”、“{”时,将其进s_bracket栈;
②遇到“}”、“]”、“)”时,判断栈顶是否是相匹配的括号
• 不是,退出扫描过程;
• 是,继续扫描exps,直到exps扫描结束。
-------------------------------------------------------------- 展开
提示:(1)设置一个括号顺序栈s_bracket(字符数组data[]存放字符表达式中的括号,整型变量top作为栈顶指针);
typedef struct stack
{
char data[MaxSize];
int top;
}s_bracket;
(2)用字符数组exps[MaxSize]存放表达式;
(3)下标i扫描表达式字符数组exps[MaxSize],忽略非括号字符,
①遇到左括号“(”、“[”、“{”时,将其进s_bracket栈;
②遇到“}”、“]”、“)”时,判断栈顶是否是相匹配的括号
• 不是,退出扫描过程;
• 是,继续扫描exps,直到exps扫描结束。
-------------------------------------------------------------- 展开
2个回答
展开全部
//参考
#include<stdio.h>
#define MaxSize 105
typedef struct hstack
{
char data[MaxSize];
int top;
}s_bracket;
int main()
{
char exps[MaxSize], tvalue;
int i, sbn = 0;
s_bracket sb;
sb.top = 0;
gets(exps);
for (i = 0; exps[i] != '\0'; ++i){
if (exps[i] == '(' || exps[i] == '{' || exps[i] == '['){
sb.data[sb.top] = exps[i];
sb.top++;
}
else if (exps[i] == ')' || exps[i] == '}' || exps[i] == ']'){
if (sb.top == 0){
break;
}
tvalue = sb.data[sb.top-1];
if ((exps[i] == ')' && '(' == tvalue) || (exps[i] == '}' && '{' == tvalue) || (exps[i] == ']' && '[' == tvalue)){
sbn++;
sb.top--;
}
}
}
if (exps[i] == '\0' && sb.top == 0){
printf ("匹配数:%d\n", sbn);
}
else {
printf ("不匹配!\n");
}
return 0;
}
展开全部
#include <stdio.h>
#include <stdlib.h>
const int MAXSIZE = 100;
typedef char SElemType;
typedef struct node {
SElemType data[MAXSIZE];
int top;
}*s_bracket;
int isFull(s_bracket S) { return S->top >= MAXSIZE; }
int isEmpty(s_bracket S) { return S->top == 0; }
int Push(s_bracket S,SElemType x) {
if(isFull(S)) return 0;
S->data[S->top++] = x;
return 1;
}
int Pop(s_bracket S,SElemType *x) {
if(isEmpty(S)) return 0;
*x = S->data[--S->top];
return 1;
}
int GetTop(s_bracket S,SElemType *x) {
if(isEmpty(S)) return 0;
*x = S->data[S->top - 1];
return 1;
}
int StackSize(s_bracket S) { return S->top; }
int main() {
s_bracket S = (s_bracket)malloc(sizeof(struct node));
char exp[MAXSIZE],bracket;
int i,matched;
printf("输入表达式:\n");
while(fgets(exp,MAXSIZE,stdin)) {
S->top = 0;
i = matched = 0;
while(exp[i]) {
if(exp[i] == '{' || exp[i] == '[' || exp[i] == '(')
Push(S,exp[i]);
if(exp[i] == '}') {
if(!isEmpty(S)) {
Pop(S,&bracket);
if(bracket == '{') ++matched;
}
}
if(exp[i] == ']') {
if(!isEmpty(S)) {
Pop(S,&bracket);
if(bracket == '[') ++matched;
}
}
if(exp[i] == ')') {
if(!isEmpty(S)) {
Pop(S,&bracket);
if(bracket == '(') ++matched;
}
}
++i;
}
printf("共匹配 %d 对。\n",matched);
printf("输入表达式(<Ctrl+Z> <Enter>结束):\n");
}
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询