数据结构—线性实习题目(二)3

括号匹配问题(栈)数据结构—线性实习题目(二)3_第1张图片

#include 
using namespace std;
#define maxSize 100
 
template
class SqStack{
private:
	int base;
	int top;
	T *data;
public:
	int top1() {
		return top;
	}
	SqStack(){
		data = new T[maxSize];
		base = 0;
		top = -1;
	}
	~SqStack() {
		delete[] data;
	}
 
	bool Push(T ch) {
		if (top >= maxSize-1) { // 判断是否栈满
			return false;
		}
		top++;
		data[top] = ch;
		return true;
	}
 
	bool Pop() {
		if (top < base) {
			return false;
		}
		top--;
		return true;
	}
	
	 T getTop() {
		if (top >= base) {
			return data[top];
		}
		else {
			return -1;
		}
	}
 
	bool IsEmpty() {
		if (top < base) {
			return true;
		}
		else return false;
	}
};
 
int main() {
	SqStack stk;
	char ch;
	cin >> ch;
	while (ch != '#') {
		if (ch == '(' || ch == '[' || ch == '{') {
			stk.Push(ch);
		}
		cin >> ch;
		if (ch == ')' || ch == '}' || ch == ']') {
			if ((int)(stk.getTop()) == (int)ch - 1 || (int)(stk.getTop()) == (int)ch - 2) {
				stk.Pop();
			}
			else {
				stk.Push(ch);
			}
		}
	}
	if (stk.top1() == -1) {
		cout << "匹配" << endl;
		return 0;
	}
	cout << "不匹配" << endl;
	return 0;
}

你可能感兴趣的:(数据结构,数据结构,算法,c++)