应用
栈的应用
验证括号的正确性
#include <iostream>
#include <string.h>
using namespace std;
typedef char ElemType;
#define MAXSIZE 100
typedef struct Stack
{
ElemType data[MAXSIZE];
int top;
}Stack;
void InitStack(Stack& S) {
S.top = -1;
}
bool StackEmpty(Stack S) {
if (S.top == -1) {
return true;
}
return false;
}
bool Push(Stack& S, ElemType x) {
if (S.top == MAXSIZE - 1) {
return false;
}
S.top++;
S.data[S.top] = x;
return true;
}
bool Pop(Stack& S, ElemType& x) {
if (S.top == -1) {
return false;
}
x = S.data[S.top];
S.top--;
return true;
}
ElemType GetTop(Stack S) {
return S.data[S.top];
}
int main() {
Stack S;
InitStack(S);
string str;
cin >> str;
//flag标志状态 true为括号匹配,false为不匹配
bool flag = true;
for (int i = 0; i < str.size(); i++) {
//元素若为{,(,[则入栈
if ((str[i] == '{') || (str[i] == '[') || (str[i] == '(')) {
Push(S, str[i]);
}//元素若为},),]则出栈 赋值给right
if ((str[i] == '}') || (str[i] == ']') || (str[i] == ')')) {
if ((str[i] == '}' && GetTop(S) == '{')
|| (str[i] == ']' && GetTop(S) == '[')
|| (str[i] == ')' && GetTop(S) == '(')) {
char top = Pop(S, top);
continue;
}
else {
Push(S, str[i]);
}
}
}
if (S.top != -1) { //当栈不为空时
flag = false;
}
if (flag == false) {
cout << "括号不匹配!" << endl;
}
else cout << "括号匹配!" << endl;
system("pause");
return 0;
}

表达式求值

队列的应用
层次遍历
队列在计算机系统中的应用
Last updated