栈括号匹配问题
前言:最近打算把数据结构过一遍,这里都做下笔记
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SUCCESS 1
#define OVERSIZE 0
#define ERROR -1
typedef int Status;
typedef int ElemType;
typedef struct _SqStack{
int iInitSize;
int iCurrentLength;
ElemType* pStack;
ElemType* pTop;
ElemType* pBottom;
}SqStack, *PSqStack;
Status initStack(SqStack* pSqStack, int iSize)
{
pSqStack->pStack = malloc(sizeof(int)*iSize);
if (pSqStack == NULL)
return ERROR;
pSqStack->iInitSize = iSize;
pSqStack->pBottom = pSqStack->pTop = pSqStack->pStack;
pSqStack->iCurrentLength = 0;
return SUCCESS;
}
Status pushElem(SqStack* pSqStack, ElemType elem)
{
// juege between top and length
if (pSqStack->iCurrentLength == pSqStack->iInitSize)
return OVERSIZE;
*pSqStack->pTop++ = elem;
pSqStack->iCurrentLength++;
return SUCCESS;
}
ElemType popElem(SqStack* pSqStack)
{
ElemType elem;
if (pSqStack->pTop == pSqStack->pBottom)
return ERROR;
elem = *--pSqStack->pTop;
pSqStack->iCurrentLength--;
return elem;
}
Status checkStackEmpty(SqStack* pSqStack)
{
if (pSqStack->pTop == pSqStack->pBottom)
return SUCCESS;
else
return ERROR;
}
// test for matching brackets
Status matchBrackets(SqStack* pSqStack, char* bracketString)
{
ElemType elem;
char* pChar = bracketString;
while (*pChar != '\0')
{
if (*pChar == '(' || *pChar == '[' || *pChar == '{')
pushElem(pSqStack, *pChar);
else{
if (*pChar == ')' || *pChar == ']' || *pChar == '}')
{
elem = popElem(pSqStack);
if (*pChar == ')')
{
if (elem == '(')
{
pChar++;
continue;
}
else
return ERROR;
}
else if (*pChar == ']')
{
if (elem == '[')
{
pChar++;
continue;
}
else
return ERROR;
}
else if (*pChar == '}')
{
if (elem == '{')
{
pChar++;
continue;
}
else
return ERROR;
}
}
}
pChar++;
}
// 这种情况是有可能多压入了相关的匹配符号,虽然前面的都能匹配到,但是这种情况也是错误的
if (checkStackEmpty(pSqStack) == 1)
{
return SUCCESS;
}
else{
return ERROR;
}
}
// test for realing stack
int main()
{
Status iStatus;
SqStack sqStack;
char bracketBuffer[0x20] = { 0 };
int iSize;
printf("init bracketBuffer -> ");
scanf("%s", bracketBuffer);
iSize = strlen(bracketBuffer);
// test for initing stack elem
initStack(&sqStack, iSize);
// test for matching brackets
// eg1. ()()
// eg2. (())(()
iStatus = matchBrackets(&sqStack, bracketBuffer);
printf("match Status -> %d\n", iStatus);
// test for inserting stack elem
/*
pushElem(&sqStack, 1);
pushElem(&sqStack, 2);
pushElem(&sqStack, 3);
pushElem(&sqStack, 4);
pushElem(&sqStack, 5);*/
// test for overflowing
// insertStackElement(&sqStack, 6);
// test for poping element
/*
printf("popStackElement -> %d\n", popElem(&sqStack));
printf("popStackElement -> %d\n", popElem(&sqStack));
printf("popStackElement -> %d\n", popElem(&sqStack));
printf("popStackElement -> %d\n", popElem(&sqStack));
printf("popStackElement -> %d\n", popElem(&sqStack));
printf("popStackElement -> %d\n", popStackElement(&sqStack));
*/
return 0;
}