在C++中实现堆栈类

Implementing a stack class in C++

本文关键字:堆栈 实现 C++      更新时间:2023-10-16

我正在尝试使用链表实现堆栈类,这是我的堆栈。

// 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 的答案