程序填空题:括号匹配
基于链栈的括号匹配。
c++
#define ERROR 0
#define OVERFLOW -2
typedef char SElemType;
typedef int Status;
typedef struct SNode {
int data;
struct SNode *next;
} SNode, *LinkStack;
Status InitStack(LinkStack &S) {
S = NULL;
return OK;
}
bool StackEmpty(LinkStack S) {
if (!S)
return true;
return false;
}
Status Push(LinkStack &S, SElemType e) {
SNode *p = new SNode;
if (!p) {
return OVERFLOW;
}
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S, SElemType &e) {
SNode *p;
if (!S)
return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
Status GetTop(LinkStack &S) {
if (!S)
return ERROR;
return S->data;
}
Status Matching() {
char ch;
SElemType x;
LinkStack S;
@@[InitStack(S)](2);
int flag = 1;
cin >> ch;
while (ch != '#' && flag)
{
switch (ch) {
case '[' :
case '(':
@@[Push(S, ch)](2);
break;
case ')':
if (@@[!StackEmpty(S) && GetTop(S) == '('](2))
Pop(S, x);
else
flag = 0;
break;
case ']':
if (@@[!StackEmpty(S)](2) && GetTop(S) == '[')
Pop(S, x);
else
flag = 0;
break;
}
cin >> ch;
}
if (@@[StackEmpty(S) && flag](2))
return true;
else
return false;
}
int main() {
LinkStack S;
int flag = (int) Matching();
if (flag)
cout << "括号匹配成功";
else
cout << "括号匹配失败";
return 0;
}
答案:
第1空:InitStack(S)
第2空:Push(S, ch)
第3空:!StackEmpty(S) && GetTop(S) == '('
第4空:!StackEmpty(S)
第5空:StackEmpty(S) && flag
c++
#define ERROR 0
#define OVERFLOW -2
typedef char SElemType;
typedef int Status;
typedef struct SNode {
int data;
struct SNode *next;
} SNode, *LinkStack;
Status InitStack(LinkStack &S) {
S = NULL;
return OK;
}
bool StackEmpty(LinkStack S) {
if (!S)
return true;
return false;
}
Status Push(LinkStack &S, SElemType e) {
SNode *p = new SNode;
if (!p) {
return OVERFLOW;
}
p->data = e;
p->next = S;
S = p;
return OK;
}
Status Pop(LinkStack &S, SElemType &e) {
SNode *p;
if (!S)
return ERROR;
e = S->data;
p = S;
S = S->next;
delete p;
return OK;
}
Status GetTop(LinkStack &S) {
if (!S)
return ERROR;
return S->data;
}
Status Matching() {
char ch;
SElemType x;
LinkStack S;
@@[InitStack(S)](2);
int flag = 1;
cin >> ch;
while (ch != '#' && flag)
{
switch (ch) {
case '[' :
case '(':
@@[Push(S, ch)](2);
break;
case ')':
if (@@[!StackEmpty(S) && GetTop(S) == '('](2))
Pop(S, x);
else
flag = 0;
break;
case ']':
if (@@[!StackEmpty(S)](2) && GetTop(S) == '[')
Pop(S, x);
else
flag = 0;
break;
}
cin >> ch;
}
if (@@[StackEmpty(S) && flag](2))
return true;
else
return false;
}
int main() {
LinkStack S;
int flag = (int) Matching();
if (flag)
cout << "括号匹配成功";
else
cout << "括号匹配失败";
return 0;
}
答案:
第1空:InitStack(S)
第2空:Push(S, ch)
第3空:!StackEmpty(S) && GetTop(S) == '('
第4空:!StackEmpty(S)
第5空:StackEmpty(S) && flag