[栈] 括号匹配问题

#include <iostream>
using namespace std;

// 定义;


struct Stack {
  char    data;
  Stack  *next;
};

// 初始化;


Stack *Init() {
  Stack *top;
  top = new Stack();
  top->next = NULL;
  return top;
}

// 进栈;


void Push(Stack *top, char e) {
  Stack *p;
  p = new Stack();
  if (!p) 
  return ;
  p->next = top->next;
  p->data = e;
  top->next = p;
}

// 出栈;


char Pop(Stack *top) {
  Stack *p;
  char e;
  if (top->next == NULL)
  return 0;
  p = top->next ;
  e = p->data;
  top->next = p->next;
  delete p;
  return e;
}


int main() {
 Stack *s, *top;
 char  ch, x;
 int m, n, t;
 m = n = t = 0;
 top = s = Init();

//   输入一个字符,判断是‘)’,‘]’(若是则进栈);若是‘(’,‘[’则从栈顶取出值进行匹配;


 while ((ch = getchar()) != 10) {
  if (ch == '[' || ch == '(') {
   Push(s, ch);
   ++m;
  }
  else if (ch == ']') {
   x = Pop(s);
   if (x != '[') {
    ++n;
    cout << "']'不匹配\n";
   }
  }
  else if (ch == ')') {
   x = Pop(s);
   if (x != '(') {
    ++n;
    cout << "')'不匹配\n";
   }
  }
 }
 cout << "括号要匹配的数量:\n";
 cout << m << endl;
    cout << "括号不匹配的数量:\n";
 cout << n << endl;
 cout << "括号匹配的数量:\n";
 cout << m - n << endl;

// 如果括号两边的数量不相符合,则多于的没有匹配的有多少;


 if (top->next != NULL) {
      while (top->next != NULL) {
    top = top->next;
    ++t; 
  }
 }
 cout << "如果两边括号数量不匹配,输出不能匹配的数量:\n";
 cout << t << endl;
  return 0;
}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值