(数据结构复习day3)
#include<iostream>
using namespace std;
const int MAXSIZE = 100;
typedef char ElemType;
typedef struct {
ElemType* top;
ElemType* base;
int stacksize;
}SqStack;
bool InitStack(SqStack& S);//初始化顺序栈
bool Push(SqStack& S, ElemType e);//将元素e压入栈内
bool Pop(SqStack& S, ElemType& e);//将首元素出栈,用元素e返回
bool GetTop(SqStack S, ElemType& e);//取得栈顶元素,用e返回
bool StackEmpty(SqStack S);//判断顺序栈是否为空
void TraverseStack(SqStack S);//自顶向下遍历栈
void TraverseStackReverse(SqStack S);//自底向上遍历栈
bool DestroyStack(SqStack& S);//销毁栈
bool matching(char exp[]);//栈的应用,括号匹配
bool InitStack(SqStack& S) {
S.base = new ElemType[MAXSIZE];
if (!S.base)return 0;
S.top = S.base;
S.stacksize = MAXSIZE;
return 1;
}
bool Push(SqStack& S, ElemType e) {
if (S.top - S.base == S.stacksize)
return 0;
*S.top = e; S.top++;
return 1;
}
bool Pop(SqStack& S, ElemType& e) {
if (S.top == S.base)
return 0;
S.top--;
e = *S.top;
return 1;
}
bool GetTop(SqStack S,ElemType& e){
if (S.base == S.top)
return 0;
S.top--;
e = *S.top;
return 1;
}
bool StackEmpty(SqStack S) {
if (S.base == S.top)
return 1;
return 0;
}
void TraverseStack(SqStack S) {
if (!StackEmpty(S)) {
S.top--;
while (S.top >= S.base) {
cout << *S.top << " ";
S.top--;
}
}
cout << endl;
}
void TraverseStackReverse(SqStack S) {
if (!StackEmpty(S)) {
S.top--;
while (S.base <= S.top) {
cout << *S.base << " ";
S.base++;
}
}
cout << endl;
}
bool DestroyStack(SqStack& S) {
S.top = S.base;
return 1;
}
bool matching(char exp[]) {
int n = strlen(exp);
SqStack S; InitStack(S);
for (int i = 0; i < n; i++) {
if (exp[i] != '(' && exp[i] != ')' && exp[i] != '[' && exp[i] != ']')
continue;
if (exp[i] == '(' || exp[i] == '[')
Push(S, exp[i]);
else {
if (StackEmpty(S))return 0;
char ch; GetTop(S, ch);
if ((ch == '(' && exp[i] == ')') || (ch == '[' && exp[i] == ']'))
Pop(S, ch);
}
}
if (StackEmpty(S))return 1;
return 0;
}
int main()
{
SqStack s1;
ElemType e;
if (InitStack(s1))
cout << "初始化字符顺序栈成功" << endl;
else
{
cout << "初始化字符顺序栈失败" << endl;
return 1;
}
cout << "输入5个字符:" << endl;
for (int i = 0; i < 5; i++) {
cin >> e;
Push(s1, e);
}
if (GetTop(s1, e))
cout << "取顺序栈栈顶元素是:" << e << endl;
if (StackEmpty(s1))
cout << "顺序栈空栈!" << endl;
else
cout << "顺序栈非空栈!" << endl;
cout << "自栈顶到栈底输出:" << endl;
TraverseStack(s1);
cout << "自栈底到栈顶输出:" << endl;
TraverseStackReverse(s1);
Pop(s1, e);
cout << "弹出栈顶元素是:" << e << endl;
if (!StackEmpty(s1)) {
cout << "弹出栈顶元素后的栈:" << endl;
TraverseStack(s1);
}
if (DestroyStack(s1))
cout << "顺序栈已销毁!" << endl;
char s[40];
cout << "输入带括号表达式:" << endl;
cin >> s;
if (matching(s))
cout << "表达式括号匹配!" << endl;
else
cout << "表达式括号不匹配!" << endl;
return 0;
}
实验样例