栈运用之括号匹配

栈的特点:后进先出

核心算法

#ifndef _STACK_H_
#define _STACK_H_
#define STACK_SIZE 100
#define INCREMENT 10
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct
{
 ElemType *base;
 ElemType *top;
 int stacksize;
}SqStack;
Status InitStack(SqStack &S);
Status DestoryStack(SqStack &S);
Status ClearStack(SqStack &S);
Status EmptyStack(SqStack &S);
Status Push(SqStack &S,ElemType e);
Status Pop(SqStack &S,ElemType &e);
Status Compare(SqStack &S);
#endif

#include"stack.h"
#include<iostream>
using namespace std;
//构造空栈
Status InitStack(SqStack &S)
{
 S.base=(ElemType*)malloc(STACK_SIZE*sizeof(ElemType));
 if(!S.base)
 {
  return OVERFLOW;
 }
 else
 {
  S.top=S.base;
  S.stacksize=STACK_SIZE;
  return OK;
 }
}
//销毁栈
Status DestoryStack(SqStack &S)
{
 ElemType e;
 if(S.top!=S.base)
 {
   Pop(S,e);
 }
 else
 {
  return OK;
 }
}
//置空栈
Status ClearStack(SqStack &S)
{
 if(S.top!=S.base)
 {
  S.top=S.base;
 }
 else
 {
  return OK;
 }
}
//清空栈
Status EmptyStack(SqStack &S)
{
 if(S.top==S.base)
 {
  return TRUE;
 }
 else
 {
  return ERROR;
 }
}
//压栈
Status Push(SqStack &S,ElemType e)
{
 if(S.top-S.base>=S.stacksize)
 {
  S.base=(ElemType*)realloc(S.base,(STACK_SIZE+INCREMENT)*sizeof(ElemType));
  if(!S.base)
  {
   return OVERFLOW;
  }
  else
  {
   S.top=S.base+S.stacksize;
   S.stacksize+=INCREMENT;
  }
 }
 else
 {
  *S.top++=e;
  return OK;
 }
}
//弹栈
Status Pop(SqStack &S,ElemType &e)
{
 if(S.top==S.base)
 {
  return ERROR;
 }
 else
 {
  e=*--S.top;
  return OK;
 }
}
//括号匹配
Status Compare(SqStack &S)
{
 ElemType e;
 int flag=TRUE;
 char ch;
 while((ch=getchar())!='$'&&flag)//$为字符串输入的结束标志
 {
  switch(ch)
  {
  case '(':
  case '[':
  case'{':
   Push(S,ch);
   break;
  case ')':
   if(Pop(S,e)==ERROR||e!='(')
   {
    flag=FALSE;
   }
   break;
  case ']':
   if(Pop(S,e)==ERROR||e!='[')
   {
    flag=FALSE;
   }
   break;
  case '}':
   if(Pop(S,e)==ERROR||e!='{')
   {
    flag=FALSE;
   }
   break;
  }
 }
 if(flag&&ch=='$'&&EmptyStack(S))
 {
  return TRUE;
 }
 else
 {
  return FALSE;
 }
}

#include"stack.h"
#include<iostream>
using namespace std;
SqStack S;
ElemType e;
int main()
{
 if(InitStack(S)==OVERFLOW)
 {
  cout<<"内存分配失败!"<<endl;
 }
 else
 {
  if(Compare(S)==TRUE)
  {
   cout<<"括号匹配成功!"<<endl;
  }
  else
  {
   cout<<"括号匹配不成功!"<<endl;
  }
 }
 DestoryStack(S);
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值