#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
int Max = 1000;
class Stack {
public:
Stack(int n);
void Push(char n);
void Pop(char& n);
char getTop();
bool IsEmpty();
bool IsFull();
private:
char* elements;
int top;
int maxsize;
void overflowprocess();
};
int SearchPairs(char* arry);
int main() {
char arry[1000];
char temp=NULL;
int cnt = 0;
while (temp != '#') {
cin >> temp;
arry[cnt] = temp;
//cout << arry[cnt] <<" " ;
cnt++;
}
int k = SearchPairs(arry);
if (k == 0)
cout << "匹配" << endl;
}
Stack::Stack(int n)
{
maxsize = n;
elements = new char[maxsize];
top = -1;
}
void Stack::Push(char n)
{
if (IsFull() == true)
overflowprocess();
top++;
elements[top] = n;
}
void Stack::Pop(char& n)
{
if (IsEmpty() == true)
cout << " 空" << endl;
n = elements[top];
top--;
}
char Stack::getTop()
{
if (top != -1)
return elements[top];
else
return 'n';
}
bool Stack::IsEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool Stack::IsFull()
{
if (top != maxsize - 1)
return false;
else
return true;
}
void Stack::overflowprocess()
{
char* newElements=new char(maxsize+maxsize);
if (newElements == NULL)
cout << "分配失败" << endl;
for (int i = 0; i <= top; i++)
newElements[i] = elements[i];
maxsize += maxsize;
delete []elements;
}
int SearchPairs(char* arry)
{
Stack s(Max);
int cnt = 0;
while (arry[cnt] != '#') {
if (arry[cnt] == '{')
s.Push('{');
else if (arry[cnt] == '[')
s.Push('[');
else if (arry[cnt] == '(')
s.Push('(');
else if (arry[cnt] == ')') {
char t;
s.Pop(t);
if (t != '(' ) {
cout << "不匹配" << endl;
return -1;
}
}
else if (arry[cnt] == ']') {
char t;
s.Pop(t);
if (t != '[') {
cout << "不匹配" << endl;
return -1;
}
}
else if (arry[cnt] == '}') {
char t;
s.Pop(t);
if (t != '{') {
cout << "不匹配" << endl;
return -1;
}
}
cnt++;
}
if(s.IsEmpty())
return 0;
else {
cout << "不匹配" << endl;
return -1;
}
}
西农数据结构作业_括号匹配问题(栈的应用)
最新推荐文章于 2024-09-10 20:37:54 发布