在C++中实现堆栈类
Implementing a stack class in C++
我正在尝试使用链表实现堆栈类,这是我的堆栈。
// File: Stack.h
#ifndef STACK_H
#define STACK_H
class Stack
{
private:
struct linklst{
int num;
int* next;
};
linklst* top;
public:
Stack();
~Stack();
void push(int i);
int pop();
bool isempty();
};
#endif
和我的堆栈.cpp
// Stack.cpp
#include"Stack.h"
using namespace std;
Stack::Stack(){
top = new linklst();
top->num = -1;
top->next = nullptr;
};
Stack::~Stack() {
linklst * r = new linklst();
while (true)
{
r = top;
top = top->next;
delete r;
}
delete top;
};
void Stack::push(int i){
linklst * r = new linklst();
r->num = i;
r->next = top;
top = r;
};
int Stack::pop(){
if (!isempty){
linklst * r = top;
top = top->next;
int x = r->num;
delete r;
return x;
}
};
bool Stack::isempty(){
return (top->next == nullptr);
};
每当我尝试将 top 分配给 r 时,我的问题就出在 cpp 文件中,例如在推送函数 r->next = top 中; 我收到此错误" 无法将 stack::linllst * 类型的值分配给 int * 类型的实体"
有谁知道我做错了什么??
任何帮助将不胜感激谢谢
将结构定义从
struct linklst{
int num;
int* next;
};
自
struct linklst{
int num;
linklst* next;
};
然而,即使在此更改之后,您的代码也会出错。例如,析构函数中存在内存泄漏
Stack::~Stack() {
linklst * r = new linklst();
while (true)
{
r = top;
top = top->next;
delete r;
}
delete top;
};
首先,您分配新的linklst并将其地址分配给r,然后在循环中重新分配r。堆栈设计中存在其他错误
例如,不需要在构造函数中分配"虚拟"顶部。我会通过以下方式定义构造函数
Stack::Stack()
{
top = NULL; // or nullptr
}
AMD 成员函数为空,如下所示
bool Stack::isempty()
{
return ( top == nullptr);
}
此外,成员函数 pop 具有未定义的行为,因为它在堆栈为空时不返回任何内容
int Stack::pop(){
if (!isempty){
linklst * r = top;
top = top->next;
int x = r->num;
delete r;
return x;
}
};
简而言之,无论堆栈需求如何,您的链接列表接口/数据结构都会略有偏差。
更准确地说,它所说的问题是最大的问题:您的类定义没有为您提供将linklist
插入linklist
的方法,但这就是您正在做的事情,我可能会非常正确地添加。
在代码行中 top = top->next;
您正在尝试分配 r
、指向linklist *
的指针 next
、指向 int 的指针。 如上所述,意图是正确的,定义是错误的。 next
应该是指向linklist
的指针。
struct linklst {
int num; // current payload
linklst* next; // pointer to the next linklst, NULL for EOL. (Not an int*)
};
更新
有关更多信息以及代码中的其他问题,请查看 Vlad 的答案
相关文章:
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 了解使用堆栈实现队列的递归调用机制
- 为堆栈实现泛型集合
- 未分配被释放的指针(将堆栈实现为链表时)
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 河内塔C++堆栈实现
- 线程安全堆栈实现
- 使用导致分段错误的类C++中的堆栈实现
- C++堆栈实现弹出函数不起作用
- 我的矩阵堆栈实现(OpenGL ES 2.0)有什么问题
- 堆栈实现C
- C 堆栈实现意外输出
- 指针数组堆栈实现
- C++ 堆栈实现硬件错误
- C++堆栈实现 - 两个版本的 top 方法
- 无法理解堆栈实现的isEmpty函数中的返回语句
- 在编写堆栈实现 c++ 时遇到问题
- 使用堆栈实现C++
- 测试《毁灭战士3》堆栈实现时堆栈损坏
- 使用 3 个堆栈实现排序.(分段错误 - 核心转储)