用C++写一个栈并判断括号是否配对
数据结构作业
#include <iostream>
using namespace std;
enum status_code {success, overflow, underflow};
template <class Type, int max>
class Stack{
public:
Stack();
bool is_full();
bool is_empty();
status_code push(Type num);
status_code pop();
status_code get_top(Type &num);
void show_all();
private:
int count;
int data[max];
};
template <class Type, int max>
Stack<Type, max>::Stack(){
count = -1;
}
template <class Type, int max>
bool Stack<Type, max>::is_full(){
return (count == max - 1);
}
template <class Type, int max>
bool Stack<Type, max>::is_empty(){
return (count == -1);
}
template <class Type, int max>
status_code Stack<Type, max>::push(Type num){
if(is_full()) return overflow;
data[++count] = num;
return success;
}
template <class Type, int max>
status_code Stack<Type, max>::pop(){
if(is_empty()) return underflow;
--count;
return success;
}
template <class Type, int max>
status_code Stack<Type, max>::get_top(Type &num){
if(is_empty()) return underflow;
num = data[count];
return success;
}
template <class Type, int max>
void Stack<Type, max>::show_all(){
for(int i = 0; i <= count; ++i){
cout << data[i] << " ";
}
cout << "\n";
}
int main(){
Stack<char, 100> stack;
string data;
char current;
cin >> data;
for(int i = 0; i < data.length(); ++i){
if(stack.get_top(current) == underflow && i) break;
switch(data[i]){
case ')':
if(current == '(') stack.pop(); break;
case ']':
if(current == '[') stack.pop(); break;
case '}':
if(current == '{') stack.pop(); break;
default:
stack.push(data[i]);
}
}
cout << (stack.is_empty() ? "括号配对" : "括号不配对");
return 0;
}