//不是原创,不知道怎么转载(笑哭) //原创在这里 //https://blog.csdn.net/weixin_44567289/article/details/93910097 //我写这个就是想自己几个笔记哈哈 #includeusing namespace std; #define MAX_SIZE 1024 //先准备一下栈 //这个好像是用数组写的栈 class Stack { public: Stack(); ~Stack(); void push_back(void*); void* Front(); void pop_front(); int GetSize(); void Clear(); bool empty(); private: void* data[1024]; int size; }; Stack::Stack() { for (int i = 0; i < MAX_SIZE; i++) { data[i] = NULL; } size = 0; } Stack::~Stack() { if (this->data) { //delete []this->data; this->size = 0; } } void Stack::push_back(void* data) { if (data == NULL) { return; } this->data[this->size] = data; ++this->size; }; //返回栈顶的元素 void* Stack::Front() { if (this->size == 0) { return NULL; } return this->data[this->size - 1]; }; void Stack::pop_front() { if (this->size == 0) { return; } this->data[this->size - 1] = NULL; --this->size; }; int Stack::GetSize() { return this->size; }; void Stack::Clear() { if (this->size == 0) { return; } for (int i = 0; i < this->size; i++) { this->data[i] = NULL; } this->size = 0; }; bool Stack::empty() { if (this->size == 0) { return true; } return false; } //---------------以上是栈的准备-------------------------- //----------------一级警报!!!----------------------- //-------------------不是演习!!!!--------------------------- //栈里似乎就存着这玩意 class Compare { public: char str; int index; }; bool CompareLeft(char str) { if (str == '(') { return true; } return false; } bool CompareRight(char str) { if (str == ')') { return true; } return false; } void PrintCompare(char* str, int index) { cout << str << endl; for (int i = 0; i < index; i++) { cout << " "; } cout << "^|" << endl; } int main() { Stack stack; char str[] = "((6+1*5))+(5+6(6*3)"; char* str2 = str; //遇左括号进栈,遇右括号出栈,判断是否是左括号,是配对成功,否则则为失败 //相当于是字符串数组的下标? int index = 0; while (*str2 != ' ') { if (CompareLeft(*str2)) { //这是干哈?? Compare* a = new Compare; a->str = *str2; a->index = index; //入栈 stack.push_back(a); } if (CompareRight(*str2)) { if (stack.GetSize() == 0) { //如果栈空了,右边没法配对了?(?是吗我不太确定) PrintCompare(str, index); break; } //这波是把左边能和他配对的取出来 Compare* s = (Compare*)stack.Front(); if (CompareLeft(s->str)) { stack.pop_front(); delete s; } } ++str2;//字符串指针后移 ++index; } int x = stack.GetSize(); for (int i = 0; i < x; i++) { //如果循环完了栈里还剩元素,说明左括号没有做匹配 Compare* s = (Compare*)stack.Front(); PrintCompare(str, s->index); stack.pop_front(); delete s; } return 0; }



