问题描述
- 关于数据结构括号匹配的问题
-
程序写完了,但是一运行就崩了,我不知道错误在哪,求大神指教!下面贴出我的代码:
#include
#include
#include
using namespace std;#define SIZE 100
typedef struct StackNode{
char data;
struct StackNode *next;
}StackNode,*LinkStack;void InitStack(LinkStack &S);
void Push(LinkStack &S,char e);
void Pop(LinkStack &S,char &e);
bool StackEmpty(LinkStack &S);
char GetTop(LinkStack &S);
void Matching(char Carray[]);void mud(LinkStack &S,char Carray[]);
void main(){
LinkStack S;
char Carray[SIZE];
cout<<"请输入一串括号并以#号结束:";
gets(Carray);
puts(Carray);
Matching(Carray);
// if(!StackEmpty(S)) cout<<"栈已空";
//else cout<<"未空";}
void InitStack(LinkStack &S){
//构造一个空栈
S=NULL;
}void Push(LinkStack &S,char e){
//压入栈
LinkStack p;
p=new StackNode;
p->data=e;
p->next=S;
S=p;
}void Pop(LinkStack &S,char &e){
//弹出栈
LinkStack p;
if(S==NULL){
printf("该栈已空n");
exit(1);
}
p=S;
e=S->data;
S=S->next;
delete p;
}bool StackEmpty(LinkStack &S){
//判断栈是否已空
if(S==NULL) return true;
else return false;
}char GetTop(LinkStack &S){
//返回桟顶元素
return S->data;
}void Matching(char Carray[]){
char x;
int flag=1,i=0;
LinkStack S;
InitStack(S);
while(Carray[i]!='#'&&flag){
switch(Carray[i]){
case '[' || '(':
Push(S,Carray[i]);
break;
case ']':
x=GetTop(S);
if(x=='[') Pop(S,x);
else flag=0;
break;
case ')':
x=GetTop(S);
if(x=='(') Pop(S,x);
else flag=0;
break;
}
i++;
}
if(!StackEmpty(S)&& flag) cout<<"括号匹配";
else cout<<"括号不匹配";}
解决方案
设置断点,单步调试跟踪一下