【发布时间】:2016-02-14 01:17:13
【问题描述】:
嘿,我的这个项目有问题。我应该从文件中读取整数并将它们插入到列表中。需要实现一个 findSpot 函数,它遍历链表,如果下一个节点的值大于正在检查的值,则返回当前的“点”。然后我们将链表输出到一个单独的文件中。
这是代码。
#include <iostream>
#include <fstream>
using namespace std;
class listNode {
public:
int value;
listNode* next;
friend class linkedList;
listNode()
: value(0)
, next(NULL)
{
}
public:
~listNode(){
};
};
class linkedList {
listNode* listHead;
public:
linkedList()
: listHead(NULL)
{
}
bool isEmpty()
{
return (listHead == 0);
}
void listInsert(int data, listNode* spot)
{
listNode* newNode;
newNode->value = data;
newNode->next = NULL;
if (isEmpty()) {
listHead = newNode;
}
else {
newNode->next = spot->next;
spot->next = newNode;
cout << newNode;
}
}
/*void listDelete ()
{
}*/
listNode* findSpot(int data)
{
listNode* spot;
spot = listHead;
while (spot->next != 0 && spot->next->value < data) {
spot = spot->next;
}
return spot;
}
void printList(listNode* spot)
{
listNode* newNode = spot;
while (newNode != NULL) {
cout << "Inserting " << newNode->value << ": "
<< "listHead-->(" << newNode->value << "," << newNode->next->value << ")-->(";
newNode = newNode->next;
}
cout << endl;
}
/*~linkedList()
{
listNode* temp = spot->next;
spot->next = spot->next->next;
delete temp;
}*/
};
int main(int argc, char* argv[])
{
int data;
listNode* spot;
ifstream infile;
infile.open(argv[1]);
ofstream outfile(argv[2]);
cout << "Reading Data from the file" << endl;
while (infile >> data) {
cout << data << endl;
}
infile.close();
linkedList myList;
infile.open(argv[1]);
while (infile >> data) {
myList.findSpot(data);
myList.listInsert(data, spot);
myList.printList(spot);
}
cout << "Printing your linked list to the output file.";
/*while (outfile.is_open())
{
myList.printList();
}*/
infile.close();
outfile.close();
return 0;
}
不知道问题主要出在insertList函数还是findSpot函数。 findSpot 函数对我来说似乎是正确的,但我可能只是遗漏了一些东西。
当我运行代码时,第一次实际读取文件没问题。实际上,将任何内容插入到链表中都会导致程序挂起。
【问题讨论】:
-
为什么你的代码里都是空行?它使阅读变得非常困难。在从文件中读取任何内容之前,您应该测试您的链表是否真的与一个小的
main函数一起使用,该函数调用插入具有硬编码值的条目,以便您(和其他人)轻松诊断.如果您的链表根本不起作用,那么担心文件读取是没有意义的。 -
哦,对不起,我想这只是一个奇怪的个人喜好。空旷的空间让我可以很容易地区分东西XD
-
请正确重新格式化和重新缩进您的代码。难道你不想让你的代码尽可能地易于理解和可读,让其他人更容易看到你做了什么,问题出在哪里?
标签: c++ linked-list insertion-sort