//头文件,4个头文件一个是节点的头文件,一个是栈的实现的头文件,一个是模拟的头文件
#ifndef LINKNODE_H
#define LINKNODE_H
#include
using namespace std;
template
class LinkNode{
public:
T data;
LinkNode
* link;
LinkNode(){
}
LinkNode(const T value, LinkNode
* str = NULL) :data(value), link(str){
}
};
#endif
#ifndef STACK_H
#define STACK_H
#include
#include"LinkNode.h" using namespace std; template
class Stack{ private: LinkNode
* head; int length; public: Stack(); ~Stack(); void Pop(); void Push(const T& data); T Top()const; bool isEmpty()const; int Size()const; void Clear(); }; template
Stack
::Stack() :head(NULL), length(0) { } template
Stack
::~Stack() { this->Clear(); } template
void Stack
::Pop() { if (!this->isEmpty()) { LinkNode
* p = head; p = p->link; delete head; head = p; } else { cout << "the stack is empty" << endl; exit(true); } } template
void Stack
::Push(const T& data) { if (this->isEmpty()) { head = new LinkNode
(data, NULL); length++; } else { LinkNode
* p = new LinkNode
(data, this->head); head = p; length++; } } template
T Stack
::Top()const { if (!this->isEmpty()) { return this->head->data; } else { cout << "the stack is empty" << endl; exit(true); } } template
bool Stack
::isEmpty()const { if (head == NULL) return true; return false; } template
int Stack
::Size()const { return length; } template
void Stack
::Clear() { LinkNode
* p = head; while (p) { p = p->link; delete head; head = p; } head = NULL; length = 0; } #endif #ifndef USER_H #define USER_H #include"Stack.h" #include
#include
class DeliMatch{ private: string value; Stack
str; char temp[1000]; int number = 1; public: DeliMatch(); ~DeliMatch(); bool Read(); bool Judge(); void Simulate(); }; DeliMatch::DeliMatch() { //默认构造函数 } DeliMatch::~DeliMatch() { //析构函数 } bool DeliMatch::Read() { ifstream cin("F:\\temp.txt"); for (int i = 0; i < this->number; i++) { cin.getline(temp, 1000); this->value = temp; } this->number++; if (this->value == "#" || this->value.empty()) return false; return true; } bool DeliMatch::Judge() { int count = this->value.length(); //该题目的主要意思没清楚,下面的函数是将所有的左括号全部入栈,遇到右括号是开始出栈 for (int i = 0; i < count; i++) { if (this->value[i] == '(' || this->value[i] == '[' || this->value[i] == '{') this->str.Push(this->value[i]); else if (this->value[i] == ')') { if (this->str.Top() == '(') this->str.Pop(); else return false; } else if (this->value[i] == ']') { if (this->str.Top() == '[') this->str.Pop(); else return false; } else if (this->value[i] == '}') { if (this->str.Top() == '{') this->str.Pop(); else return false; } else continue; } return true; } void DeliMatch::Simulate() { //该函数来模拟全过程 while (this->Read()) { if (this->Judge()) { cout << "succeed!" << endl; } else cout << "loser!" << endl; } } #endif //主函数 #include"User.h" int main(int argc, char argv[]) { DeliMatch user; user.Simulate(); return 0; }
关于栈的应用,完全基于类的实现
最新推荐文章于 2022-02-22 18:02:01 发布