数据结构实验之栈四:括号匹配
题目描述
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入
输入数据有多组,处理到文件结束。
输出
如果匹配就输出“yes”,不匹配输出“no”
示例输入
sin(20+10) {[}]
示例输出
yes
no
链表的方法,较为复杂。需要建立链栈,将数组代替栈的方法换为了线性表
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<iostream>
using namespace std;
typedef char anytype;
struct stacks
{
struct node //链栈
{
anytype data;
struct node *next;
}*head;
stacks() //构造链
{
head=new node;
head->next=NULL;
}
bool empty() //判断是否为空栈
{
if(head->next)
return false;
return true;
}
void push(anytype n) //入栈
{
struct node *p;
p=new node;
p->data=n;
p->next=head->next;
head->next=p;
}
void pop() //出栈
{
struct node *p;
p=head->next;
if(p)
{
head->next=p->next;
free(p);
}
}
anytype top() //查询栈顶元素
{
if(!empty())
return head->next->data;
return 0;
}
};
bool isbrackets(char ch) //判断输入的是否为括号
{
if(ch==')'||ch=='('||ch==']'||ch=='['||ch==')'||ch=='(')
return true;
return false;
}
bool tocheck(stacks &s,char ch) // 检查是否与栈顶括号匹配
{
if(s.empty())
{
return false;
}
switch(ch)
{
case ')':
if(s.top()=='(')
return true;
return false;
case ']':
if(s.top()=='[')
return true;
return false;
case '}':
if(s.top()=='{')
return true;
return false;
default :
return false;
}
}
int main()
{
ios::sync_with_stdio(false);
string str;
while(getline(cin,str,'\n'))
{
stacks s;
bool mark=true;
int len=str.length();
for(int i=0; i<len; i++)
{
if(isbrackets(str[i]))
{
if(str[i]=='('||str[i]=='['||str[i]=='{') //左括号入栈
s.push(str[i]);
else if(tocheck(s,str[i])) //右括号如果与栈顶匹配则弹出栈顶左括号
s.pop();
else
{
mark=false; //标记括号不匹配
break;
}
}
}
if(s.empty()&&mark)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}
数组(栈)的方法,简单明白
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <ctype.h>
#include <cstring>
#include <stack>
using namespace std;
int main()
{
char f[60],t;
int i;
while(gets(f)!=NULL)
{
stack <char> s;
int v=1;
for(i=0;i<strlen(f);i++)
{
if(f[i]=='('||f[i]=='['||f[i]=='{')
s.push(f[i]);
if(f[i]==')'||f[i]==']'||f[i]=='}')
{
if(s.empty())
{v=0;break;}
else
{
t=s.top();s.pop();
if(f[i]==')')
if(t!='(')
{v=0;break;}
if(f[i]==']')
if(t!='[')
{v=0;break;}
if(f[i]=='}')
if(t!='{')
{v=0;break;}
}
}
}
if(!s.empty())
v=0;
if(v)
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}