From 4ab346a607066ff8ee37284eaa6de9f5f7646594 Mon Sep 17 00:00:00 2001 From: mi84kabv9 Date: Sat, 8 Jun 2024 17:44:26 +0800 Subject: [PATCH] ADD file via upload --- Stack.h | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Stack.h diff --git a/Stack.h b/Stack.h new file mode 100644 index 0000000..a011df6 --- /dev/null +++ b/Stack.h @@ -0,0 +1,63 @@ +template +class Stack; + +// 节点定义 +template +class Node { +private: + T info; + Node* next; +public: + friend class Stack; + Node() : next(nullptr) {}; + Node(T item, Node* nextnode = NULL) { + info = item; + next = nextnode; + } + Node(Node& node) { + info = node.info; + next = node.next; + } +}; + +// 栈定义 +template +class Stack { +private: + Node* top; +public: + Stack() { + top = NULL; + } + bool push(const T& item) { + Node* p = top; + top = new Node; + top->info = item; + top->next = p; + return true; + } + bool pop() { + if (top == NULL) return false; + else { + Node* p = top; + top = top->next; + delete p; + } + return true; + } + T peek() { + return top->info; + } + ~Stack() { + Node* p = top; + while (top) { + top = top->next; + delete p; + p = top; + } + top = p = NULL; + } + bool empty() { + return top == NULL; + } +}; \ No newline at end of file