您的位置:首页 > 理论基础 > 数据结构算法

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

2016-12-31 13:12 399 查看
//用栈括号匹配的问题 

//采用的存储结构为顺序存储结构 

#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;

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: