自己写了一个链栈操作,来实现括号匹配算法,但是程序运行不下去!求大神指教!
#include<iostream>#include<string.h>
#include<ctype.h>
using namespace std;
typedef struct snode
{
char elem;
struct snode *next;
}Link,*Linkstack;
//Linkstack top;
int init_stack(Linkstack top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
int empty(Linkstack top)//1空返回1,非空返回0
{
if(top->next==NULL)
return 1;
else
return 0;
}
void push_stack(Linkstack top,char a)//压栈
{
Linkstack s;
s=(Linkstack )malloc(sizeof(Link));
s->elem=a;
s->next=top->next;
top->next=s;
}
int pop_stack(Linkstack top,char a)//出栈
{
if(empty(top))
{
cout<<"栈空!"<<endl;
return 0;
}
Linkstack s;
s=(Linkstack )malloc(sizeof(Link));
s=top->next;
a=s->elem;
top->next=s->next;
free(s);
return 1;
}
char getop(Linkstack top)//取栈顶元素,返回给a
{
char a;
if(empty(top))
cout<<"栈空!"<<endl;
a=top->next->elem;
return a;
}
int main()
{
Linkstack top;
int i,length;
char a,ch,str[100];
cout<<"请输入要检测的括号对!"<<endl;
cin>>str;
length=strlen(str);
for(i=0;i<length;i++)
{
if(str[i]=='('||str[i]=='['||str[i]=='{') /*如果是({【则入栈*/
push_stack(top,str[i]);
else
{
if(!empty(top))
{
ch=getop(top);
if(ch=='('&&str[i]==')'||ch=='['&&str[i]==']'||ch=='['&&str[i]==']')
pop_stack(top,a);
else
{
cout<<"括号不匹配!"<<endl;
return 0;
}
}
else
{
cout<<"括号不匹配!"<<endl;
return 0;
}
}
}
if(i==length&&empty(top))
cout<<"括号匹配!"<<endl;
else
cout<<"括号不匹配!"<<endl;
return 0;
}