簡體   English   中英

單鏈接列表C ++ ostream和istream —輸出內存地址

[英]Singly linked list C++ ostream and istream — outputs memory addresses

我對此確實很陌生,現在正在學習單鏈表。 我正在寫一些代碼,但我真的很困惑。 我正在嘗試編寫一個讀取方法和一個寫入方法。 我有一個無法更改的測試裝置。 我只希望能夠讀取流並輸出流,這樣它就不會隨內存地址一起返回。

誰能以一種非常簡單的方式進行解釋,並幫助我修復此代碼?

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

謝謝!

您的寫入方法似乎有些混亂。 您要編寫元素,而不是創建新元素。 這樣的事情應該更好地工作:

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方法連續兩次被調用,舊列表將被丟棄而不釋放內存。 您應該考慮在保存另一個文件的同時調用write時您的類應該做什么。 追加嗎? 首先刪除舊列表?

在Write()方法中,通過執行以下操作來破壞整個列表

Node *node = new Node;
head = node;

如果您問我,這將整個列表替換為一個空列表。 NumberOfInts不再正確,您將繼續打印相同的節點->數據NumberOfInts次。

我不知道從哪里開始。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM