头文件:(另存为SeqStack.h)
typedef struct
{
DataType stack[MaxStackSize];
int top;
} SeqStack;
void StackInitiate(SeqStack *S) /*初始化顺序堆栈S*/
{
S->top = 0; /*定义初始栈顶下标值*/
}
int StackNotEmpty(SeqStack S)
/*判顺序堆栈S非空否,非空则返回1,否则返回0*/
{
if(S.top <= 0) return 0;
else return 1;
}
int StackPush(SeqStack *S, DataType x)
/*把数据元素值x压入顺序堆栈S,入栈成功则返回1,否则返回0 */
{
if(S->top >= MaxStackSize)
{
printf("堆栈已满无法插入! \n");
return 0;
}
else
{
S->stack[S->top] = x;
S->top ++;
return 1;
}
}
int StackPop(SeqStack *S, DataType *d)
/*弹出顺序堆栈S的栈顶数据元素值到参数d ,出栈成功则返回1,否则返回0*/
{
if(S->top <= 0)
{
printf("堆栈已空无数据元素出栈! \n");
return 0;
}
else
{
S->top --;
*d = S->stack[S->top];
return 1;
}
}
int StackTop(SeqStack S, DataType *d)
/*取顺序堆栈S的当前栈顶数据元素值到参数d ,成功则返回1,否则返回0*/
{
if(S.top <= 0)
{
printf("堆栈已空! \n");
return 0;
}
else
{
*d = S.stack[S.top - 1];
return 1;
}
}
括号问题
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MaxStackSize 100
typedef char DataType;
#include "SeqStack.h"
void ExpIsCorrect(char exp[], int n)
//判断有n个字符的字符串exp左右括号是否配对正确
{
SeqStack myStack; //定义链式堆栈
int i;
char c;
StackInitiate(&myStack);
for(i = 0; i < n; i++)
{
if((exp[i] == '(') || (exp[i] == '[') || (exp[i] == '{'))
StackPush(&myStack, exp[i]); //入栈
else if(exp[i] == ')' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c == '(')
StackPop(&myStack, &c); //出栈
else if(exp[i] == ')' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c != '(')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(exp[i] == ']' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c == '[')
StackPop(&myStack, &c); //出栈
else if(exp[i] == ']' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c != '[')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(exp[i] == '}' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c == '{')
StackPop(&myStack, &c); //出栈
else if(exp[i] == '}' && StackNotEmpty(myStack)
&& StackTop(myStack, &c) && c != '{')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(((exp[i] == ')') || (exp[i] == ']') || (exp[i] == '}'))
&& !StackNotEmpty(myStack))
{
printf("右括号多于左括号!\n");
return;
}
}
if(StackNotEmpty(myStack))
printf("左括号多于右括号!\n");
else
printf("左右括号匹配正确!\n");
}
void main(void)
{
char a[] = "(())abc{[)(]}"; //测试例子1。左右括号配对次序不正确
char b[] = "(()))abc{[]}"; //测试例子2。右括号多于左括号
char c[] = "(()()abc{[]}"; //测试例子3。左括号多于右括号
char d[] = "(())abc{[]}"; //测试例子4。左右括号匹配正确
int n1 = strlen(a);
int n2 = strlen(b);
int n3 = strlen(c);
int n4 = strlen(d);
ExpIsCorrect(a, n1);
ExpIsCorrect(b, n2);
ExpIsCorrect(c, n3);
ExpIsCorrect(d, n4);
}
二者放于同一目录下即可
温馨提示:内容为网友见解,仅供参考