知识框架
基本操作代码
#include <iostream>
using namespace std;
#define MaxSize 10
typedef struct {
int data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S){
S.top=-1;
}
bool Empty(SqStack S){
return S.top == -1;
}
bool push(SqStack &S,int e){
if (S.top == MaxSize-1){
return false;
}
S.data[++S.top] = e;
return true;
}
bool pop(SqStack &S,int &e){
if (S.top == -1){
return false;
}
e = S.data[S.top--];
return true;
}
bool GetTop(SqStack S,int &e){
if (S.top == -1){
return false;
}
e = S.data[S.top];
return true;
}
typedef struct {
int data[MaxSize];
int top0;
int top1;
}ShStack;
void InitShStack(ShStack &S){
S.top0 = -1;
S.top1 = MaxSize;
}
typedef struct LinkNode {
int data;
struct LinkNode *next;
}LinkNode,*LiStack;
int main() {
SqStack S;
InitStack(S);
for (int i = 0; i < 5; ++i) {
push(S,i);
}
int n = S.top+1;
int e;
for (int i = 0; i < n; ++i) {
pop(S,e);
cout<<e<<" ";
}
cout<<endl;
return 0;
}
栈在括号匹配中的应用
bool bracketCheck(char str[],int length){
SqStack S;
InitStack(S);
for (int i = 0; i < length; ++i){
if (str[i] == '('||str[i] == '{'||str[i] == '['){
push(S,str[i]);
} else {
if (Empty(S)){
return false;
}
char ch;
pop(S,ch);
if (str[i] == ')' && ch != '('){
return false;
}
if (str[i] == ']' && ch != ']'){
return false;
}
if (str[i] == '}' && ch != '{'){
return false;
}
}
}
return Empty(S);
}
栈在表达式求值中的应用
- 中缀转后缀
- 中缀转前缀
栈在递归中的应用