数据结构学习:链栈实现括号匹配
使用链栈来判断输入的括号是否左右匹配
//联系,使用栈结构来判断输入的括号是否符合规则
#include
using namespace std;
typedef struct LinkNode
{
char data;
struct LinkNode *next;
}LinkNode; //链栈结点定义
typedef struct
{
LinkNode *top;
}LinkStack;//定义链栈头指针
//初始化链栈
void InitStack(LinkStack &S)
{
S.top = (LinkNode *)malloc(sizeof(LinkNode));
S.top->next = NULL;
}
//链栈指针由栈顶指向栈底
//新元素入栈
bool Push(LinkStack &S,char x)
{
LinkNode *q = (LinkNode *)malloc(sizeof(LinkNode));
q->data = x;
q->next = S.top->next;//链栈插入新元素
S.top = q; //栈顶指针指向新节点
return true;
}
//元素出栈
bool Pop(LinkStack &S,char &x)//出栈对元素采用&操作
{
if(S.top == NULL)
return false; //栈空
LinkNode *q = (LinkNode *)malloc(sizeof(LinkNode));
q = S.top->next;
x = q->data; //元素出栈
S.top->next = q->next; //栈顶指针后移
free(q);
return true;
}
bool EmptyStack(LinkStack S)
{
if(S.top->next == NULL)
return true;
else
return false;
}
bool bracketChack(char str[],int length)//判断括号是否符合标准
{
LinkStack S;
InitStack(S);
for(int i = 0;i<length;i++)
{
if(str[i] == ‘(’ || str[i] == ‘[’ || str[i] == ‘{’)
{
Push(S,str[i]);
}
else
{
if(EmptyStack(S))
return false;
char topElem;
pop(S,topElem);
if(str[i] == ‘(’ && topElem !=’)’)
return false;
if(str[i] == ‘[’ && topElem !=’]’)
return false;
if(str[i] == ‘{’ && topElem !=’}’)
return false;
}
}
return EmptyStack(S);
}
int main()
{
char str[100];
int len = 0;
char ch;
for(int i = 0;i<100;i++)
{
cin>>str[i] ;
ch = getchar();
if(ch == ‘\n’)//回车结束
break;
len++;
}
if(bracketChack(str))
cout<<“括号符合标准”<<endl;
else
cout<<“不符合标准”<<endl;
return 0;
}