【问题标题】:reason why it doesn't works on visual 2019为什么它不适用于视觉 2019 的原因
【发布时间】:2020-07-13 16:19:26
【问题描述】:

我认为编码语法或组合没有问题。我用手画了好几遍,没有发现什么特别的问题。我已经尝试过很多次了。 我试图一遍又一遍地重复,但是当我使用 Visual Studio 2019 版本时,它只是立即关闭,运行窗口上没有任何输出。我已经用谷歌搜索了好几次,但我找不到我想要的解决方案。 我是否需要重新安装可视程序或必须操作额外的选项? 请给出一些解决方案

#include<iostream>
using namespace std;
#include<stdlib.h>

class Node {
    public:
    int data;
    Node * next;
};
class Stack {
    public:
    Node *top;
    Stack() {
        top->next = NULL;
    }
    void push(int data);
    int pop();
    void show();
};
void Stack::push(int data)
{
    Node *node = new Node;
    node->data = data;
    if (top->next == NULL) {
        node->next = NULL;
        top->next = node;
    }
    else {
        node->next = top->next;
        top->next = node;
    }
}
int Stack::pop()
{
    if (top-> next == NULL) {
        cout << "stack empty" << endl;
        return 0;
    }
    Node *temp = new Node;

    temp = top->next;
    int data = temp->data;
    top->next = temp->next;
    delete temp;
    return data;
}

void Stack::show() {
    Node *cur = new Node;
    cur = top-> next;
    while (cur != NULL) {
        cout << cur-> data << "->";
        cur = cur-> next;
    }

}
int main() {
    Stack s;
    s.push(5);
    s.push(1);
    s.push(3);
    s.show();
    cout << endl;
    cout << s.pop() << endl;

    s.show();
    return 0;
}

【问题讨论】:

  • edit您的问题并添加代码作为文本。另外,解释“不起作用”....访问help center并阅读How to Ask
  • 您的最小代码和错误必须在问题中并且必须是文本。你的链接也不适合我。
  • 另一方面,该链接可能对我有用,但在上帝的绿色地球上,我不可能冒着被感染的风险点击它来找出答案。
  • 可能是你在Visual Studio中发现了一个bug,需要更新。您的程序可能有错误。你认为哪个更有可能?由于您尚未发布代码并且您的链接对我不起作用,我不知道
  • @JohnnyMopp 我解决了我的问题,请看一下

标签: c++ visual-studio-code visual-studio-2019


【解决方案1】:

在你的构造函数中

Stack() {
    top->next = NULL;
}

top 从未被赋予过值,因此top-&gt;next 是一个错误。

在我看来,如果您始终将 top-&gt;next 替换为 top,您的大部分代码都会得到修复。

这里还有一个错误

void Stack::show() {
    Node *cur = new Node;
    cur = top-> next;

您将cur 分配给一个新节点,然后您忘记了这一点并将其分配给下一行的其他内容。就这样做

void Stack::show() {
    Node *cur = top-> next;

(但top-&gt; next 应该只是top,如上所述)。

这里也是同样的错误

Node *temp = new Node;

temp = top->next;

如果在下一行为temp 分配了其他内容,为什么要为temp 分配一个新节点?

这是你的代码将修复所有错误(我认为)

class Stack {
    public:
    Node *top;
    Stack() {
        top = NULL;
    }
    void push(int data);
    int pop();
    void show();
};
void Stack::push(int data)
{
    Node *node = new Node;
    node->data = data;
    node->next = top;
    top = node;
}
int Stack::pop()
{
    if (top == NULL) {
        cout << "stack empty" << endl;
        return 0;
    }
    Node *temp = top;
    int data = temp->data;
    top = temp->next;
    delete temp;
    return data;
}

void Stack::show() {
    Node *cur = top;
    while (cur != NULL) {
        cout << cur-> data << "->";
        cur = cur-> next;
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多