以下是使用 C++ 完成的代码: ```cpp #ifndef __lk_stack_h__ #define __lk_stack_h__ #include "node.h" // 结点类模板 // 链栈类模板 template<class elemtype> class linkstack { protected: // 数据成员: node<elemtype> *top; // 栈顶指针 int count; // 元素个数 public: // 抽象数据类型方法声明及重载编译系统默认方法声明: linkstack(); // 无参数的构造函数模板 virtual ~linkstack(); // 析构函数模板 bool empty() const; // 判断栈是否为空 void traverse(void (*visit)(const elemtype &)) const; // 遍历栈 bool push(const elemtype &e); // 入栈 bool top(elemtype &e) const; // 返回栈顶元素 bool pop(elemtype &e); // 出栈 // 链栈类模板的实现部分 template<class elemtype> linkstack<elemtype>::linkstack() { top = NULL; // 初始化栈顶指针为空 count = 0; // 元素个数初始化为 0 } template<class elemtype> linkstack<elemtype>::~linkstack() { node<elemtype> *p; while (top!= NULL) { p = top; top = top->next; delete p; } } template<class elemtype> bool linkstack<elemtype>::empty() const { return top == NULL; } template<class elemtype> void linkstack<elemtype>::traverse(void (*visit)(const elemtype &)) const { node<elemtype> *p = top; while (p!= NULL) { visit(p->data); p = p->next; } } template<class elemtype> bool linkstack<elemtype>::push(const elemtype &e) { node<elemtype> *p = new node<elemtype>; p->data = e; p->next = top; top = p; count++; return true; } template<class elemtype> bool linkstack<elemtype>::top(elemtype &e) const { if (top == NULL) { return false; } e = top->data; return true; } template<class elemtype> bool linkstack<elemtype>::pop(elemtype &e) { if (top == NULL) { return false; } node<elemtype> *p = top; e = top->data; top = top->next; delete p; count--; return true; } }; #endif ``` 1. 注意内存的分配和释放,避免内存泄漏。 2. 对于边界情况,如空栈时的操作,要进行充分的错误处理。 3. 测试代码的各种功能,确保其正确性和稳定性。 [2024-12-21 20:36:07 | AI写代码神器 | 725点数解答]