数据结构--利用栈判断括号匹配

/*下午打球去了,虐菜了*/
 
 <pre name="code" class="cpp">#ifndef _MATCH_H_
#define _MATCH_H_  
 
#include<iostream>  
#include<string.h>  
#include<assert.h>  
using namespace std;
    
typedef char ElemType;  
#define STACK_INIT_SIZE 50 
  
typedef struct Stack  
{  
    ElemType *base;  
    int top;  
    int stacksize;  
    int capacity;  
}Stack;


void InitStack(Stack *st);
bool IsEmpty(Stack *st); 
bool IsFull(Stack *st);  
bool Push(Stack *st,ElemType x);  
bool Pop(Stack *st);  
//ElemType GetTop(Stack *st,ElemType *x);
 ElemType GetTop(Stack *stack);
#endif   
#include"match.h"


void InitStack(Stack *st)  
{  
    st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);  
    assert(st->base != NULL);  
    st->capacity = STACK_INIT_SIZE;  
    st->top = 0;  
}  
bool IsFull(Stack *st)  
{  
    return st->top >= st->capacity;  
}  
  
bool IsEmpty(Stack *st)  
{  
    return st->top == 0;  
}  
bool Push(Stack *st, ElemType x)  
{  
    if(IsFull(st))  
    {  
        cout<<"栈已满,"<<x<<"不能入栈!"<<endl;  
        return false;  
    }  
    st->base[st->top++] = x;  
    return true;  
}  
  
bool Pop(Stack *st)  
{  
    if(IsEmpty(st))  
    {  
        cout<<"栈已空,不能出栈!"<<endl;  
        return false;  
    }  
  
    st->top--;  
    return true;  
}  
   
/*ElemType GetTop(Stack *st,ElemType *x)    
{    
    if(IsEmpty(st))    
    {    
        cout<<"栈为空:"<<endl;    
        return false;    
    }    
    *x = st->base[--st->top];//   *x = st->base[st->top--]; 效果是一样的吗?  
   // cout<<"栈顶是:"<<*x<<endl;//不必要的输出  
    return *x;    
}  */
ElemType GetTop(Stack *stack)  
{  
    if(IsEmpty(stack))  
    {  
        cout<<"栈空!"<<endl;  
    }  
    return stack->base[stack->top-1];  
}  

#include"match.h"

  
void main()
{
	Stack st;
	char str[1000];
	ElemType item;
	InitStack(&st);
    cin>>str;
    //[]
	int len = strlen(str);

	int i = 0;
	int flag = 1;
	while(i < len)
	{
		if(str[i] == '[' || str[i] == '(' || str[i] == '{')
			Push(&st,str[i]);
		else if(str[i] == ']')
		{
		//	if(IsEmpty(&st)||GetTop(&st, &item) != '[')
			if(IsEmpty(&st)||GetTop(&st ) != '[')
				flag = 0;
			else 
				Pop(&st);
		}
		else if(str[i] == ')')
		{
		//	if(IsEmpty(&st)||GetTop(&st,&item) != '(')
			if(IsEmpty(&st)||GetTop(&st ) != '(')
				flag = 0;
			else 
				Pop(&st);
		}
		else if(str[i] == '}')
		{
			//if(IsEmpty(&st)||GetTop(&st, &item) != '{')
			if(IsEmpty(&st)||GetTop(&st ) != '{')
				flag = 0;
			else 
				Pop(&st);
		}
		i++;
	}
	
  
if(!IsEmpty(&st))  
    {  
        flag = 0;  
    }     
    if(flag == 1)  
        cout<<" 括号匹配 "<<endl; 
    else  
    {  
        cout<< "括号不匹配"<<endl;   
    }  	
} 



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值