酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

第9关:栈的热身训练 100 任务要求 记录 评论 关卡排行榜 任务描述 输入样本: 任务描述 这是一次链式栈的热身训练,为后面的进阶做准备。本次训练目标是建立一个链式栈,实现链式栈的建立、判空、入栈和出栈 输入样本: 测试输入:3(链式栈的长度),1,2,4; 预期输出:1 2 4 1 2 (出栈后) 使用c++语言完成填补完整 #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() // 操作结果:构造一个空栈表 { } template<class elemtype> linkstack<elemtype>::~linkstack() // 操作结果:销毁栈 { } template<class elemtype> bool linksta

以下是使用 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点数解答]

相关提问