我们应该使用 C++ 中的堆栈结构为我的 CS 类实现一个程序来检查给定表达式中的大括号、方括号和括号是否都匹配。不幸的是,我有点坚持这个,因为我一直告诉我有些东西不匹配,即使它最明确地匹配。这是我到目前为止得到的:
#include <stdlib.h>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
struct cell {int value; cell* next; };
cell* top;
int numElem;
void init()
{
top = NULL;
numElem = 0;
}
int pop()
{
int res;
if (top != NULL)
{
res = top -> value;
top = top -> next;
numElem--;
} else {
cout << "FAIL: Stack empty!\n";
res = -1;
}
return res;
}
void push(int element)
{
cell* cat = new cell;
cat -> value = element;
cat -> next = top;
top = cat;
}
void match(char expr[])
{
bool pass = true;
char expected;
char encountered;
char closing;
for (int i=0; pass && (i<strlen(expr)); i++)
{
if ((i==40)||(i==91)||(i==123))
push(i);
else
{
if (i==41)
expected = 40;
if (i==93)
expected = 91;
if (i==125)
expected = 123;
encountered = pop();
if (expected != encountered)
closing = i;
pass = false;
}
}
if (pass)
cout << "Parentheses match OK!\n";
else
cout << encountered << " has opened, but closing " << closing;
cout << " encountered!\nParentheses do not match\n";
}
int main(int argc, char * argv[])
{
init();
match(argv[1]);
return 0;
}
由于堆栈框架存在于先前的练习中并且在那里运行良好,我强烈假设应该存在任何错误void match