ITPub博客

首页 > 应用开发 > IT综合 > C++,利用链式栈实现括号匹配,界面友好,操作方便,运行流畅

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

IT综合 作者:小梁124 时间:2014-11-19 16:40:57 0 删除 编辑

     #include

  #include

  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;

  }

  }文章来源:http://www.mfqyw.com/

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29870867/viewspace-1339184/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Bootstrap学习笔记
请登录后发表评论 登录
全部评论

注册时间:2014-09-11

  • 博文量
    71
  • 访问量
    214129