數據結構--利用棧判斷括號匹配

/*下午打球去了,虐菜了*/
 
 <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;   
    }  	
} 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章