c++ - 如何修复我的链表读取不一致?

标签 c++ linked-list

在最近的一个项目中,我一直在使用链表重新创建一个堆栈,并且一直在尝试输出链表中的任何内容,但是它拒绝输出堆栈头部以外的任何内容。虽然这通常不会让我烦恼,但我使用了一种非常相似的方法来测试我的删除功能,它可以正常工作。 对于上下文,每个节点都包含一个 char 或 int 变量以及一个下一个指针,该节点的默认构造函数将其设为 NULL。我有 And 值(一个 int)和 Or 变量(一个 char)的访问器和修改器。

主要.cpp

#include "node.h"
#include "lilis.h"
#include <iostream>
using namespace std;

int main()
{
    lilis obj;
    char a = '%';
    char b = '+';
    char c = '=';
    char d = '-';
    obj.addPush(a);
    obj.addPush(b);
    obj.addPush(c);
    obj.addPush(d);
    obj.display();
    //obj.rePop();

    return 0;
}

百合花

#ifndef LILIS_H
#define LILIS_H

class lilis
{
    private:
        node* head;
    public:
        lilis();
        lilis(node* dupe);
        lilis(lilis& dup);
        void addPush(int a);
        void addPush(char b);
        void rePop();
        void display();
};

#endif

lilis.cpp(最后注释的代码块是我试图开始工作的,我替换了它所以它不会无限循环)

#include "node.h"
#include "lilis.h"
#include "iostream"
using namespace std;

lilis::lilis()
{
    //ctor
}

lilis::lilis(node* dupe)
{
    head=dupe;
}

lilis::lilis(lilis& dup)
{
    //ctor
    head = dup.head;
}

void lilis::addPush(int a)
{
    node* after;
    node* store = head;
    after->setAnd(a);
    after->setNext(head);
    head=after;

}

void lilis::addPush(char b)
{
    node* after;
    node* store = head;
    after->setOr(b);
    after->setNext(head);
    head=after;

}

void lilis::rePop()
{
    node* storage = head;
    cout << head->getOr();
    head = head->getNext();
    cout << head->getAnd();
    delete storage;
}

void lilis::display()
{
    node* after = head;
    cout << after->getOr();
    after = after->getNext();
    cout << after->getOr();
    /*while (after->getNext()!=NULL){
        std::cout << " " <<after->getAnd();
        after = after->getNext();
    }*/
}

最佳答案

您的代码包含多个内存实例化问题。 首先,head 变量应该在构造函数中初始化,因为它是一个指针(例如:head = nullptr)。

这个函数也有同样的问题:

void lilis::addPush(int a)
{
    node* after;
    node* store = head;
    after->setAnd(a);
    after->setNext(head);
    head=after;
}

变量未初始化后,指针可能包含一些随机值。你应该像这样重写它:

void lilis::addPush(int a)
{
    node* after = new node(); // instanciate a new node, that will be kept in memory after this function returns
    after->setAnd(a);
    after->setNext(head);
    head=after;
}

显示功能非常接近。 然而,仍然存在一个主要问题:当您的列表没有元素(例如 head 为 null)时,您必须处理显示和 rePop 函数的情况。

祝你好运!

提示:lilis(node* dupe); 是无用的:node 是一些内部的东西,它不应该暴露在公共(public)接口(interface)中,删除它或至少将其设为私有(private)...

关于c++ - 如何修复我的链表读取不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59019954/

相关文章:

c++ - DirectX11 阴影贴图问题

c++ - 将 std::List 与对象指针一起使用

java - 从单链表中删除节点

c++ - 链表数组 C++

c - 从 stdin 获取值并将其存储在链表节点中

c++ - 无符号字符数组以键入 STL::map 或其他容器

C++11 std::list 拼接后迭代器失效

c# - 为什么 LinkedList 通常比 List 慢?

c++ - 创建指针数组和分配的问题

c - 销毁C中的链表