mirror of
https://github.com/happyflyer/wangdao-data-structure.git
synced 2026-05-01 06:01:41 +08:00
完成栈的应用
This commit is contained in:
95
ch3/stack-applications/bracket_matching.cpp
Normal file
95
ch3/stack-applications/bracket_matching.cpp
Normal file
@@ -0,0 +1,95 @@
|
||||
#include <stdio.h>
|
||||
#include <string>
|
||||
#define MaxSize 10
|
||||
typedef struct
|
||||
{
|
||||
char data[MaxSize];
|
||||
int top;
|
||||
} SqStack;
|
||||
|
||||
void InitStack(SqStack &S)
|
||||
{
|
||||
S.top = -1;
|
||||
}
|
||||
|
||||
bool StackEmpty(SqStack S)
|
||||
{
|
||||
return S.top == -1;
|
||||
}
|
||||
|
||||
bool StackFull(SqStack S)
|
||||
{
|
||||
return S.top == MaxSize - 1;
|
||||
}
|
||||
|
||||
bool Push(SqStack &S, char x)
|
||||
{
|
||||
if (StackFull(S))
|
||||
{
|
||||
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--];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool GetTop(SqStack &S, char &x)
|
||||
{
|
||||
if (StackEmpty(S))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
x = S.data[S.top];
|
||||
return true;
|
||||
}
|
||||
|
||||
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 (StackEmpty(S))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
char topElem;
|
||||
Pop(S, topElem);
|
||||
if (str[i] == ')' && topElem != '(')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (str[i] == ']' && topElem != '[')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (str[i] == '}' && topElem != '{')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return StackEmpty(S);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
char c[MaxSize + 1] = {"({([])}[])"};
|
||||
printf("%d\n", bracketCheck(c, MaxSize));
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user