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

时间:2013-02-14 13:35:01

标签: 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

2 个答案:

答案 0 :(得分:1)

您的原始代码可能存在多个问题。鉴于上面的讨论和一些回复,我建议从更简单的开始。让它工作,然后逐步扩展它,直到你有你原来的目标。

我首先要实现一个非常简单的单链表而不使用类。定义一个包含指向同一类型结构和数据字段的指针的结构(可能只是一个整数)。

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

然后演示迭代列表。 C中一个非常常见的习语如下:

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

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

一旦你对此感到满意,一定要将它包装在一个类中并添加push_back()和push_front()等方法,并重载一些运算符。

但请确保您在基础知识方面做得很好。

答案 1 :(得分:0)

Node::next(Node *p)功能有什么作用? 如果它将this的下一个字段设置为p,则push_front函数中的此代码可能不正确:

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

应该:

  1. p.next设为_head。 (现在跟随p
  2. _head设为p。 (新头是p
相关问题