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