链式栈实现括号匹配问题

#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;
 }
    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/iteye_16572/article/details/81888669
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞