0

私は他のポストからここに移動しています。しかし、今回はある種の出力を得ることができました。しかし、ノードを反復処理して、出力でどのように表示されるかをノードに個別に出力させることはできません。これが私がこれまでに持っているものであり、プログラムが出力するもののスクリーンショットでもあります。

ここに画像の説明を入力してください

LList.h

#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;
        LList *front;       //points to front of the list
};

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

    _head = 0;
    _tail = 0;
    front = 0;
}

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

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

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

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

LList & LList::operator=(const LList &l)
{
    _head = l._head;
    _tail = l._tail;
    front = l.front;
    return *this;
}

inline LList::~LList()
{
}


#endif

maind.cpp

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

using namespace std;

ostream& operator<<(ostream& out, const LList& llist);

int main( )
{
    LList a;

    a.push_back(  "30" );
    a.push_front( "20" );
    a.push_back(  "40" );
    a.push_front( "10" );
    a.push_back(  "50" );

    cout << "list a:\n" << a << '\n';
    return 0;
}

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

    return out;
}
4

3 に答える 3

1
out << p -> next;

この行は最初の要素をスキップし、最後の要素で未定義の動作 (おそらく segfault) を引き起こします。これはする必要がありますout<<p

于 2013-02-14T04:44:06.917 に答える
1

に割り当てられていoperator<<ないため、何も出力されません。LList::front常にヌルです。

于 2013-02-14T04:46:04.353 に答える
1

あなたのプッシュアルゴリズムは意味がありません。リストの後ろに何かをプッシュするにはhead、リストが空の場合にのみ変更する必要がありますが、次のものが必要です。

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

リストに既にエントリが含まれているのに、なぜに設定_headするのですか? pあなたのコードには多くの同様のバグがあります - ロジックが正しくありません。

最後はおそらく次のようになります。

if (_head == 0)
    _head = p;

先頭にすでにノードがある場合、末尾にエントリを追加しても、先頭にはまったく影響しません。

于 2013-02-14T04:50:10.800 に答える