标签:lib tac use ror warning 初始化 null warnings 文件
引用栈的顺序存储,实现括号匹配问题查找:
头文件:
#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\n",errMsg); printf("%s\n",str); int len = p - str; for (int i = 0; i < len; i ++){ printf(" "); } printf("A\n"); } void test(){ const char *str = "5+)5*(6)+9/(3*1)-(1)+3()"; //初始化栈 void *stack = Init_SeqStack(); char *p = (char *)str; while (*p != ‘\0‘){ //如果是左括号,直接入栈 if (IsLeft(*p)){ Push_SeqStack(stack, p); } //如果是右括号,会有两种情况出现: 1栈不为空,匹配成功,把栈中当前字符弹出 //2栈不为空,右括号没有匹配左括号 if (IsRight(*p)){ if (Size_SeqStack(stack) > 0){ Pop_SeqStack(stack); } else{ printError(str, "没有匹配的左括号!", p); } } p++; } //判断栈是否为空 while (Size_SeqStack(stack) > 0){ //获得栈顶元素 char *pChar = (char *)Top_SeqStack(stack); //弹出栈顶元素 Pop_SeqStack(stack); //输出错误信息 printError(str, "没有匹配的右括号!", pChar); } } int main(){ test(); system("pause"); return EXIT_SUCCESS; }
标签:lib tac use ror warning 初始化 null warnings 文件
原文地址:http://www.cnblogs.com/w-x-me/p/6782921.html