C语言实现顺序栈基本操作(以括号是否配对为例为例)
通过调用简单函数实现顺序表的相关操作。代码编译环境为VS2019 16.9.4。因为VS的某些原因,scanf写为了scanf_s,作用是一样的,在其他编译环境中可将scanf_s改回去,gets_s同理。
代码功能:读入 一个字符串,判断其中的“{” 和 “}”,“[” 和 “]”,“(” 和 “)”是否配对
#include<stdio.h> //输入输出头文件
#include<stdlib.h> //标准头文件
#include<stdbool.h> //布尔类型头文件
#define MaxSize 100
typedef char Elemtype;
typedef struct
{
Elemtype data[MaxSize]; //存放栈中的数据元素
int top; //栈顶指针,即存放栈顶元素在data数组中的下标
}SqStack; //顺序栈类型
bool InitStack(SqStack*& s); //初始化栈
bool DestroyStack(SqStack*& s); //销毁栈
bool StackEmpty(SqStack*& s); //判断栈是否为空
bool Push(SqStack*& s, Elemtype e); //进栈
bool Pop(SqStack*& s, Elemtype& e); //出栈
bool GetTop(SqStack* s, Elemtype& e); //取栈顶元素
int main(int argc, const char* argv[])
{
SqStack* s;
Elemtype e;
char str[MaxSize];
bool flag = true;
InitStack(s); //初始化栈
printf("请输入一个字符串:\n");
gets_s(str, MaxSize);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == '{' || str[i] == '[' || str[i] == '(') { //当为左括号时进栈
Push(s, str[i]);
continue;
}
else if (str[i] == '}' || str[i] == ']' || str[i] == ')') {
if (GetTop(s, e)) { //当不为空时,并且此时元素与栈顶元素相匹配时,出栈
if (e == '{' && str[i] == '}')
Pop(s, e);
else if(e == '[' && str[i] == ']')
Pop(s, e);
else if(e == '(' && str[i] == ')')
Pop(s, e);
else { //当此时元素与栈顶元素不匹配时
flag = false;
break;
}
}
else { //此时右括号多余,括号不配对
flag = false;
break;
}
}
//当此时str[i]不为括号时直接跳过
}
if (!StackEmpty(s)) //当栈不为空时,此时左括号多余
flag = false;
if (flag)
printf("在该字符串中,括号是配对的。\n");
else
printf("在该字符串中,括号不配对。\n");
DestroyStack(s); //销毁栈
return 0;
}
bool InitStack(SqStack*& s)
{
s = (SqStack*)malloc(sizeof(SqStack));
if (s == NULL) //如果申请失败,返回“假”
return false;
s->top = -1; //此时栈内无元素
return true;
}
bool DestroyStack(SqStack*& s)
{
free(s);
return true;
}
bool StackEmpty(SqStack*& s)
{
if (s->top == -1) //当栈不为空时返回“真”,否则返回“假”
return true;
else
return false;
}
bool Push(SqStack*& s, Elemtype e)
{
if (s->top == MaxSize - 1) //当栈满时返回假
return false;
s->top++; //栈顶上移,并在该位置放入新的栈顶元素
s->data[s->top] = e;
return true;
}
bool Pop(SqStack*& s, Elemtype& e)
{
if (s->top == -1) //当栈为空时无法出栈,返回“假”
return false;
e = s->data[s->top];
s->top--;
return true;
}
bool GetTop(SqStack* s, Elemtype& e)
{
if (s->top == -1) //当栈为空时栈内没有元素,返回“假”
return false;
e = s->data[s->top];
return true;
}