引用栈的顺序存储,实现括号匹配问题查找:
头文件:
#pragma once #include<string.h> #include<stdlib.h> #define MAX 1024 //顺序栈 struct SeqStack{ void *data[MAX]; int size; }; #ifdef __cplusplus extern "C"{ #endif //初始化栈 void *Init_SeqStack(); //入栈 void Push_SeqStack(void *stack, void *data); //出栈 void Pop_SeqStack(void *stack); //获得大小 int Size_SeqStack(void *stack); //获得栈顶元素 void *Top_SeqStack(void *stack); //销毁栈 void Destroy_SeqStack(void *stack);
头文件实现:
#include"SeqStack.h" //初始化栈 void *Init_SeqStack(){ struct SeqStack *stack = malloc(sizeof(struct SeqStack)); stack->size = 0; for (int i = 0; i < MAX; i ++){ stack->data[i] = 0; } return stack; } //入栈 void Push_SeqStack(void *stack, void *data){ if (0 == stack){ return; } if (0 == data){ return; } struct SeqStack *s = (struct SeqStack *)stack; if (s->size == MAX){ return; } s->data[s->size] = data; s->size++; } //出栈 void Pop_SeqStack(void *stack){ if (0 == stack){ return; } struct SeqStack *s = (struct SeqStack *)stack; s->size--; } //获得大小 int Size_SeqStack(void *stack){ if (0 == stack){ return -1; } struct SeqStack *s = (struct SeqStack *)stack; return s->size; } //获得栈顶元素 void *Top_SeqStack(void *stack){ if (0 == stack){ return NULL; } struct SeqStack *s = (struct SeqStack *)stack; return s->data[s->size - 1]; } //销毁栈 void Destroy_SeqStack(void *stack){ if (0 == stack){ return; } free(stack); }
测试函数:
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<string.h> #include<stdlib.h> #include"SeqStack.h" int IsLeft(char ch){ return ch == '('; } int IsRight(char ch){ return ch == ')'; } void printError(const char *str,const char *errMsg, const char * p){ printf("Error:%s ",errMsg); printf("%s ",str); int len = p - str; for (int i = 0; i < len; i ++){ printf(" "); } printf("A "); } void test(){ const char *str = "5+)5*(6)+9/(3*1)-(1)+3()"; //初始化栈 void *stack = Init_SeqStack(); char *p = (char *)str; while (*p != '