0

私はこれに本当に慣れておらず、現在、単一リンクリストを学習しています。私はいくつかのコードを書いていますが、本当に混乱しています。読み取りメソッドと書き込みメソッドを作成しようとしています。テストハーネスがありますが、変更できません。ストリームを読み取ってストリームを出力できるようにしたいだけなので、メモリアドレスが返されません。

誰かが本当に簡単な方法で説明して、このコードを修正するのを手伝ってもらえますか?

void SLLIntStorage::Read(istream& r)
{
    char c[13];
    r >> c;
    r >> NumberOfInts;

    Node *node = new Node;
    head = node; //start of linked list

    for(int i = 0; i < NumberOfInts; i++) //this reads from the file and works
    {
        r >> node->data;
        cout << node->data << endl;
        node ->next = new Node; //creates a new node
        node = node->next;
    }
}

void SLLIntStorage::Write(ostream& w)
{
    Node *node = new Node;
    head = node;

    for(int i = 0; i < NumberOfInts; i++)
    {
        w << node->data << endl;
        //cout << i << endl;
    }
}

そしてヘッダーファイルで

#pragma once

#include <iostream>

using namespace std;

struct Node
{
    int data; //data in current node
    Node *next; //link of address to next node
};

class SLLIntStorage
{

private:
    Node *head;// start of linked list
    //Node *tail;
    Node current; //current node
public:
    void setReadSort(bool);
    void sortOwn();

    void Read(istream&);
    void Write(ostream&);

    void add(int i);
    void del();

    bool _setRead;
    int NumberOfInts;

    SLLIntStorage(void);
    ~SLLIntStorage(void);
};

inline ostream& operator<< (ostream& out, SLLIntStorage& n) 
{
    n.Write(out); 
    return out;
}
inline istream& operator>> (istream& in, SLLIntStorage& s) 
{
    s.Read(in); 
    return in;
}

ありがとう!

4

2 に答える 2

3

あなたの書き込み方法は少し混乱しているようです。新しい要素を作成するのではなく、要素を記述したい。このようなものがうまくいくはずです:

void SLLIntStorage::Write(ostream& w)
{
    Node *node = head;

    for(int i = 0; i < NumberOfInts; i++)
    {
        w << node->data << endl;
        node = node->next;
        //cout << i << endl;
    }
}

ちなみに、あなたの実装が私にとってうまくいくように見える方法では、潜在的に大きなメモリリークがあります。Readメソッドが2回続けて呼び出されると、メモリを解放せずに古いリストが破棄されます。別のファイルが保存されているときにwriteが呼び出された場合、クラスが何をするかを考える必要があります。それを追加しますか?最初に古いリストを削除しますか?

于 2011-04-25T18:52:51.403 に答える
1

Write()メソッドでは、次のようにしてリスト全体を壊します。

Node *node = new Node;
head = node;

あなたが私に尋ねれば、これはリスト全体を空のリストに置き換えます。NumberOfIntsは正しくなくなり、同じノード->データのNumberOfInts回の印刷に進みます。

どこから始めたらいいのかわからない。

于 2011-04-25T18:53:24.900 に答える