【发布时间】:2011-08-12 12:21:45
【问题描述】:
我对此真的很陌生,现在正在学习单链表。我正在写一些代码,但我真的很困惑。我正在尝试编写读取方法和写入方法。我有一个我无法更改的测试工具。我只是希望能够读取流并输出流,这样它就不会返回内存地址。
谁能用非常简单的方式解释一下并帮我修复这段代码?
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;
}
谢谢!
【问题讨论】:
-
在您的 write 方法中,我看不到您在链表中的位置。看起来您缺少“node = node->next;”在你的循环中。如所写,您将重复写入相同的整数。
-
你的测试输入是什么,当你运行它时你得到什么输出。另一件事是您的 Write 方法似乎没有遍历列表。只是一遍又一遍地打印相同的节点数据。看起来您的 Write 方法也将头节点设置为新节点。这将清除列表。
-
另外,为什么要在write方法中创建节点?您的存储对象中应该已经有一个链表;即 SLLIntStorage::head。事实上,您的 write 方法会导致您现有的存储在用新节点覆盖“head”时泄漏。你的 write 方法应该假设“head”已经被你的 read 方法初始化了。
标签: c++ linked-list istream ostream