c++ - 无法在 C++ 中遍历我的链表

标签 c++ linked-list singly-linked-list

<分区>

我已经为此工作了一段时间,但我似乎无法弄清楚如何正确地遍历我的链表。现在,我可以运行程序,它运行了,但我没有从链表中得到任何结果。到目前为止,这是我的代码 这是应该发生的事情。 enter image description here

这是我的结果。 enter image description here但这也会立即崩溃

#ifndef LList_h
#define LList_h

#include <iostream>
#include "node.h"

class LList
{
public:
    LList(void);            //constructor
    LList(const LList &);   //copy constructor
    ~LList();           //destructor

    LList *next;            //points to next node
    void push_back(const string &str);
    void push_front(const string &str);
    friend ostream& operator<<(ostream& out, const LList& llist);
    LList &operator=(const LList &l);       
private:
    Node *_head;
    Node *_tail;

    string _str;
};

inline LList::LList(void) {
    cerr << "head = tail = 0 at 0024f8d0\n";

    _head = 0;
    _tail = 0;
}

inline void LList::push_back(const string &_str) {
    Node *p = new Node(_str);
    if (_tail == 0) {
        _tail = p;
    } else {
        _tail ->next(p);
        _tail = p;
    }        
}

inline void LList::push_front(const string &_str) {
    Node *p = new Node(_str);

    if (_head == 0) {
        _head  = p;
    } else {
        _head ->next(p);
        _head = p;
    }
}

ostream &operator <<( ostream &out, const LList & llist ) {
    for( LList *p = llist.front; p != 0; p = p -> next )
        out << p;

    return out;
}

LList & LList::operator=(const LList &l) {
    _head = 0;
    _tail = 0;

    return *this;
}
#endif

最佳答案

看来您的原始代码中可能存在多个问题。鉴于上面的讨论和一些回应,我建议从更简单的事情开始。让它发挥作用,然后逐渐扩展它,直到您拥有最初的目标。

我将从不使用类的情况下实现一个非常简单的单向链表开始。定义一个结构,其中包含一个指向相同类型结构的指针和一个数据字段(可以只是一个整数)。

为此结构创建三个左右的变量并将它们链接在一起,以便第一个指向第二个,第二个指向第三个,第三个指向 NULL(通过它可以识别列表的末尾)。

然后演示遍历列表。 C中一个很常见的习语如下:

for (ptr = &first; ptr; ptr = ptr->next)
{
   printf("%p %d\n", ptr, ptr->data);
}

确保您了解其工作原理并使用它来熟悉指针以及链表的工作原理。练习使用调试器单步执行列表,并确保您了解到达列表末尾时循环如何终止。

一旦您对此感到满意,请务必将其包装在一个类中并添加 push_back() 和 push_front() 等方法,并重载一些运算符。

但首先要确保您的基础知识扎实。

关于c++ - 无法在 C++ 中遍历我的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14876036/

相关文章:

c++ - getch 结合 while-loop 两次触发 loopcontent

c++ - std::pair 引用

c - 插入排序函数不会列出排序后的所有元素

java - 不知道如何实现仅最后一个节点作为引用的循环链表

c++ - 创建 C++ 类的新实例,结果重复

c++在一个函数参数中使用按位或 "|"的多个枚举

c++ - 函数 C::add() 中不允许将 'C *' 隐式转换为 'A *'

Java链表搜索方法

c++ - 为什么这段代码在 Linux 中运行良好但在 Windows 中却失败了?

复制指向函数中结构体的指针(链表)