以下是使用 C++ 完成上述链栈类模板的实现: ```cpp #include <iostream> template<class elemtype> class node { public: elemtype data; node<elemtype> *next; node(const elemtype &d) : data(d), next(nullptr) {} }; // 链栈类模板 template<class elemtype> class linkstack { protected: // 数据成员: node<elemtype> *top; // 栈顶指针 int count; // 元素个数 public: // 无参数的构造函数模板 linkstack() { top = nullptr; count = 0; } // 析构函数模板 ~linkstack() { node<elemtype> *p = top; while (p) { node<elemtype> *q = p; p = p->next; delete q; } } // 判断栈是否为空 bool empty() const { return top == nullptr; } // 遍历栈 void traverse(void (*visit)(const elemtype &)) const { node<elemtype> *p = top; while (p) { (*visit)(p->data); p = p->next; } } // 入栈 bool push(const elemtype &e) { node<elemtype> *newNode = new node<elemtype>(e); newNode->next = top; top = newNode; count++; return true; } // 返回栈顶元素 bool top(elemtype &e) const { if (empty()) { return false; } e = top->data; return true; } // 出栈 bool pop(elemtype &e) { if (empty()) { return false; } node<elemtype> *p = top; e = top->data; top = top->next; delete p; count--; return true; } }; // 测试函数 int main() { linkstack<int> s; s.push(1); s.push(2); s.push(4); int e; if (s.pop(e)) { std::cout << e << " "; } if (s.pop(e)) { std::cout << e << " "; } return 0; } ``` 1. 注意内存的申请和释放,避免内存泄漏。 2. 对于边界情况,如空栈时的操作,要进行充分的错误处理。 3. 在进行遍历和出栈操作时,要注意指针的移动和节点的删除顺序。 [2024-12-21 20:36:04 | AI写代码神器 | 667点数解答]