数据结构(八) 用顺序栈解决括号匹配的问题

来源:互联网 发布:java中反射的应用 编辑:程序博客网 时间:2024/05/16 04:56
//用栈括号匹配的问题 
//采用的存储结构为顺序存储结构 
#include <iostream>
 
using namespace std;
#define MAXSIZE 100 
//栈的结构体
struct Node
{
int *base;
int *top;
int stackSize;
}; 
//初始化栈的操作
 void initStack(struct Node &S)
 {
  S.base = new int [MAXSIZE];
  if(S.base == NULL)
  {
  cout<<"地址分配失败\n";
  exit(1);
  }
  S.top = S.base;
  S.stackSize = MAXSIZE;
 }
 //入栈操作
void push(struct Node &S,int e)
{
if(S.top-S.base == S.stackSize)
{
cout<<"此栈已经满了\n";
exit(1);
}
*S.top++ = e;

//出栈操作
void pop(struct Node &S,int &e)
{
if(S.top==S.base)
{
//cout<<"栈为空\n";
cout<<"不能匹配\n";
exit(1);
}
e = *--S.top;

void function(struct Node S)
{
char c;
cout<<"输入你要匹配的括号(以#作为结束符)\n";
cin>>c;
int e;
while(c!='#')
{
if(c=='<'||c=='('||c=='['||c=='{')
{
push(S,c);
}
else if(c=='>')
{
pop(S,e);
if(e!='<')
{
cout<<"不能匹配\n";
exit(1);
}
}
else if(c==']')
{
pop(S,e);
if(e!='[')
{
cout<<"不能匹配\n";
exit(1);
}
}
else if(c=='}')
{
pop(S,e);
if(e!='{')
{
cout<<"不能匹配\n";
exit(1);
}
}
else if(c==')')
{
pop(S,e);
if(e!='(')
{
cout<<"不能匹配\n";
exit(1);
}
}
cin>>c;
}
if(S.top==S.base)
{
cout<<"能够匹配\n";
}
else
{
cout<<"不能匹配\n";
}
}
 int main()
 {
  struct Node S;
initStack(S);
function(S);
  return 0;
 }
0 0
原创粉丝点击