链式栈实现括号匹配问题

#include<stdlib.h>
#include<string.h>
#include<iostream>

using namespace std;

#define FALSE 1

typedef struct StackNode{
  char op;
  StackNode * next;
}StackNode,*StackTop;

char operation[50];int length;

//链式栈栈顶
StackTop top=(StackNode *)malloc(sizeof(StackNode));

//初始化链式栈
void InitialStack()
{
  top->next=NULL;
}

//判断栈是否为空
bool IsEmpty()
{
  bool flag_bool;
  top->next==NULL?flag_bool=true:flag_bool=false;
  return flag_bool;
}

//将栈顶元素Pop,并返回栈顶元素值
char Pop()
{
  StackNode * temp=(StackNode *)malloc(sizeof(StackNode));
  temp=top->next;
  if(temp==NULL)return FALSE;
  char op=temp->op;
  top->next=temp->next;
  free(temp);
  return op;
}

//取栈顶元素值
char GetTop()
{
  return top->next==NULL?FALSE:top->next->op;
}

//将新元素压入栈
void Push(char char_op)
{
  StackNode * temp=(StackNode *)malloc(sizeof(StackNode));
  temp->op=char_op;
  temp->next=top->next;
  top->next=temp;
}

//判断括号与栈顶的左括号是否匹配
bool Match(char op1,char op2)
{
  if((op1=='('&&op2==')')||(op1=='{'&&op2=='}')||(op1=='['&&op2==']'))
    return true;
  else
    return false;
}

void procExecute()
{
  length=strlen(operation);
  for(int i=0;i<length;i++)
 {
   switch(operation[i]){
     case '(':
     case '{':
     case '[':
     Push(operation[i]);
     break;
     case ')':
     case '}':
     case ']':
     if(IsEmpty()){
       cout<<"右括号多余\n";
       return;
     }else{
         if(Match(GetTop(),operation[i])){
            Pop();break;
         }
         else{
            cout<<"左右括号不匹配\n";
            return;
         }
      }
    }
  }
  if(IsEmpty())
     cout<<"括号匹配成功!\n";
  else
     cout<<"左括号多余\n";
 }

int main()
{
  while(cin>>operation)
  {
    InitialStack();
    procExecute();
  }
  return 0;
 }
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值