C++栈的应用_就近匹配
#include <iostream>
using 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 PrintCpmpare(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 !='\0')
{
if (CompareLeft(*str2))
{
Compare*a = new Compare;
a->str = *str2;
a->index = index;
stack.push_back(a);
}
if (CompareRight(*str2))
{
if (stack.GetSize()==0)
{
PrintCpmpare(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();
PrintCpmpare(str, s->index);
stack.pop_front();
delete s;
}
return 0;
}
效果图: