【问题标题】:How to fix the inconsistent reading of my linked list?如何解决我的链表读取不一致的问题?
【发布时间】:2020-03-20 01:02:53
【问题描述】:

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

main.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;
}

lilis.h

#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();
    }*/
}

【问题讨论】:

  • 你为什么要建立自己的链表?有 std::liststd::forward_list 可供使用。另外,为什么要使用链表?这是一个非常低效的数据结构。在大多数情况下,只需使用 std::vector

标签: c++ linked-list


【解决方案1】:

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

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

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

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 为空)它的显示和 rePop 函数。

祝你好运!

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2015-03-12
    • 1970-01-01
    相关资源
    最近更新 更多