读书人

括号婚配无法实现

发布时间: 2013-10-27 15:21:49 作者: rapoo

括号匹配,无法实现
#include<stdio.h>
int main()
{
int i,j,m;
char a[10],b[10],c[10];
for(i=0;i<11;i++)
scanf("%c",c[i]);
if(c[i]='(')
a[j]=c[i];
if(c[i]=')')
b[m]=c[i];
else
printf("输入出错\n");
printf("%d\n",j);
printf("%d\n",m);

if(j=m)
printf("(等于)\n");
printf("%d\n",j);
printf("%d\n",m);

return 0;
}
[解决办法]
可以用到栈来处理,给个C++的实现:

#include <iostream>
#define MAXSIZE 50
using namespace std;
typedef char ElemType;

struct SqStack
{
ElemType Data[MAXSIZE];
int top;
};

//初始化栈
void InitStack(SqStack* &stack)
{
stack = new SqStack;
stack->top = -1;
}

//销毁栈
void DestroyStack(SqStack* &stack)
{
delete stack;
}

//判断栈是否为空
bool Empty(SqStack* stack)
{
return stack->top == -1;
}

//入栈
bool Push(SqStack* &stack, ElemType e)
{
if (stack->top == MAXSIZE - 1)
return false;

stack->top++;
stack->Data[stack->top] = e;
return true;
}

//出栈
bool Pop(SqStack* &stack, ElemType &e)
{
if (stack->top == -1)
return false;

e = stack->Data[stack->top];
stack->top--;
return true;
}

//取栈顶元素
bool GetTop(SqStack* stack, ElemType &e)
{
if (stack->top == -1)
return false;

e = stack->Data[stack->top];
return true;
}


//判断表达式中的小括号()是对匹配
bool Match(char * Expresion)
{
SqStack* Stack = NULL;//初始化栈
InitStack(Stack);

int Length = strlen(Expresion);

int i = 0;
while (Expresion[i] != '\0')
{
ElemType Elem;
if (Expresion[i] == '(')//如果是左括号,则将其入栈
{
Push(Stack, '(');
}
else if (Expresion[i] == ')')//如果是右括号,则从栈中弹出一个左括号
{
if (Stack->top == -1)
return false;
Pop(Stack, Elem);
}
i++;
}

if (Empty(Stack))//栈空则匹配
return true;
else
return false;
}

int main()
{
char Expresion[] = "()(()()())";
if (Match(Expresion))
{
cout << "匹配!" << endl;
}
else
{
cout << "不匹配!" << endl;
}

system("pause");
return 0;
}


重点看下 Match()这个函数。
[解决办法]
引用:
这代码....呵呵....

确实有点乱,我改了一下看看合不合你的意思
代码:
#include<stdio.h>
int main()
{
int i,j=0,m=0,k;
char a[10],b[10],c[10];
for(i=0;i<10;i++)
scanf("%c",&c[i]);
for(k=0;k<10;k++){
if(c[k]=='(')
{
a[j]=c[k];
++j;
}
if(c[k]==')')
{
b[m]=c[k];
++m;
}
if(c[k]!='(' && c[k]!=')')
printf("error\n");
}
printf("%d\n",j);
printf("%d\n",m);

if(j==m)
printf("(等于)\n");
printf("%d\n",j);
printf("%d\n",m);

return 0;
}

读书人网 >C语言

热点推荐