C++,利用链式栈实现括号匹配,界面友好,操作方便,运行流畅



#include<iostream>
#include<string>
using namespace std;

struct Node
{
 char ch;
 Node* next;
 Node(char c, Node* p){ ch = c; next = p; }
};

void main()
{
 string str;
 bool flag = true;
 while (flag)
 {
  cout << "请输入算术表达式:" << endl;
  getline(cin, str);
  int len = str.length();
  Node* top = NULL;
  int i;
  for (i = 0; i < len; i++)
  {
   if (str[i] == '(' || str[i] == '[' || str[i] == '{')
   {
    top = new Node(str[i], top);
   }
   if (str[i] == ')' || str[i] == ']' || str[i] == '}')
   {
    if (top == NULL){ cout << "1.括号不匹配!" << endl; break; }
    else
    {
     Node* pt = top;
     top = top->next;
     pt->next = NULL;
     char item = pt->ch;
     delete pt;
     if ((item == '('&&str[i] != ')') || (item == '['&&str[i] != ']') || (item == '{'&&str[i] != '}'))
     {
      cout << "2.括号不匹配!" << endl; break;
     }
    }
   }
  }
  if (i == len)
  {
   if (top){ cout << "3.括号不匹配!" << endl; }
   else cout << "括号完全匹配!" << endl;
  }
  if (top)
  {
   Node* ptr;
   while (top)
   {
    ptr = top->next;
    delete top;
    top = ptr;
   }
  }
  cout << "是否继续?继续请按1,退出请按0:" << endl;
  int choice;
  cin >> choice;
  getchar();
  if (choice == 0)flag = false;
 }
}

代码已经过测试,在VS2013上成功运行!

发此文有两大目的:

1.和大家交流经验,供需要的人参考。

2.在下菜鸟,代码中难免有不妥之处,恳求大神批评指正。您的批评就是在下提高的起点,对于您的批评,在下将不胜感激!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值