顺序栈
定义
#define MaxSize 10
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;
初始化
void InitStack(SqStack &S)
{
S.top=-1;
}
判空
bool StackEmpty(SqStack &S)
{
if(S.top==-1)
return true;
return false;
}
入栈
bool Push(SqStack &S,ElemType x)
{
if(S.top == MaxSize-1)
return false;
S.data[++S.top]=x;
return true;
}
出栈
bool Pop(SqStack &S,ElemType &x)
{
if(S.top==-1)
return false;
x = S.data[S.top]
S.top--;
return true;
}
获取栈顶元素
bool GetTop(SqStack &S,ElemType &x)
{
if(S.top == -1)
return false;
x = S.data[S.top];
return true;
}
链栈
定义
typedef struct LinkNode
{
ElemType data;
struct LinkNode *next;
}*LStack;
初始化
bool InitLStack(LStack &L)
{
L = (StackNode*)malloc(sizeof(StackNode));
if(L == NULL)
return false;
L->next = NULL;
return true;
}
判空
bool LStackEmpty(LStack L)
{
if(L->next == NULL)
return true;
return false;
}
入栈
bool Push(LStack &L,ElemType e)
{
StackNode *node = (StackNode*)malloc(sizeof(StackNode));
if(node == NULL)
return false;
node->data = e;
node->next = L->next;
L->next = node;
return true;
}
出栈
bool Pop(LStack &L,ElemType &e)
{
if(L->next == NULL)
return false;
StackNode *node = L->next;
e = node->data;
L->next = node->next;
free(node);
return true;
}
获取栈顶元素
bool getTop(LStack &L,ElemType &e)
{
if(L->next == NULL)
return false;
e = L->next->data;
return true;
}
经典题练习
sdut括号匹配
括号匹配
#include<bits/stdc++.h>
using namespace std;
const int MaxSize = 50+5;
typedef struct
{
char data[MaxSize];
int top;
} sqStack;
void InitStack(sqStack &S)
{
S.top=-1;
}
bool StackEmpty(sqStack &S)
{
return S.top==-1;
}
bool Push(sqStack &S,char x)
{
if(S.top==MaxSize-1)
return false;
S.data[++S.top] = x;
return true;
}
bool Pop(sqStack &S,char &x)
{
if(StackEmpty(S))
return false;
x = S.data[S.top];
S.top--;
return true;
}
int main()
{
bool legal;
sqStack S;
string str;
while(getline(cin,str))
{
legal = true;
InitStack(S);//初始化栈
for(int i = 0; i < str.length(); i++)
{
if(str[i] == '(' || str[i] == '[' || str[i]=='{')
{
Push(S,str[i]);
}
else if(str[i] == ')' || str[i] == ']' || str[i] == '}')
{
if(StackEmpty(S))
{
legal = false;
break;
}
char topElem;
Pop(S,topElem);
if(topElem == '(' && str[i] !=')')
legal = false;
if(topElem == '[' && str[i] !=']')
legal = false;
if(topElem == '{' && str[i] !='}')
legal = false;
if(legal == false)
break;
}
}
if(legal == true && StackEmpty(S))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;
}
return 0;
}