【发布时间】:2021-11-28 23:24:21
【问题描述】:
我以最少的方式实现堆栈。在这个程序中,我从 valgrind 得到一个错误。 push() 和 main() 函数有问题。当我添加删除 st;对于 push() 函数,我得到更多错误。我通过 valgrind ./a.out 检查它。抱歉,代码太长了。我还为堆栈编写了其余的函数。但是它们没有错误,我把那些留在代码中可能有错误的地方。
#include <cstring>
#include <iostream>
struct Stack {
int data;
int min;
Stack* next;
};
void Push(Stack** top, int n) {
Stack* st = new Stack();
st->data = n;
if (*top == NULL) {
*top = st;
(**top).min = n;
} else {
st->min = ((n <= (**top).min) ? n : (**top).min);
st->next = *top;
*top = st;
}
std::cout << "ok" << std::endl;
}
void Pop(Stack** top) {
if (*top != NULL) {
std::cout << (**top).data << std::endl;
*top = (*top)->next;
} else {
std::cout << "error" << std::endl;
}
}
int main() {
Stack* top = nullptr;
int m;
std::cin >> m;
std::string str;
for (int i = 0; i < m; ++i) {
std::cin >> str;
if (str == "push") {
int value;
std::cin >> value;
Push(&top, value);
}
if (str == "pop") {
Pop(&top);
}
}
delete top;
}
【问题讨论】:
-
为什么
Push和Pop不是Stack的成员函数?为什么要创建一个Stack类,其中一半的函数与类外的堆栈相关(封装不好)?此外,避免内存泄漏的方法是不编写引入它们的代码。std::stack<int>是一个堆栈类,它接受整数并且没有内存泄漏。 -
我是 C++ 编程新手。我曾经用 Python 编写。请不要严格判断。是的,这可能是一个糟糕的封装,但我被要求这样写。我被要求自己实现所有功能。
-
Stack的next成员变量在*top == NULL时未初始化。在 C++ 中初始化对象的新实例的惯用方式是定义一个构造函数,这样实例化和初始化是一起完成的。 -
那你基本上是在学习
C,而不是C++。要求退款。在这个 C++ 时代,代码不应该像你被要求写的那样。 -
Push中有一个new,所以Pop中应该有一个delete。