所以,嘿,我有这个项目我有一个问题。我应该从文件中读取整数并将它们插入到列表中。有一个findSpot函数需要实现遍历链表,并且如果下一个节点的值大于被检查的值,它将返回当前的“点”。然后我们输出链接列表到一个单独的文件。C++单链接列表插入排序
这是代码。
#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'函数,该函数可以调用硬编码值插入条目,以便您(和其他人)很容易诊断。如果你的链表完全不起作用,那么担心文件阅读是没有意义的。 – PaulMcKenzie
哦,对不起,我想这只是一个奇怪的个人偏好。空的空间使得我可以很容易地区分彼此的东西XD – user2444400
请重新格式化并重新合适您的代码。你不想让自己的代码尽可能理解和可读吗?让别人更容易看到你做了什么,以及问题出在哪里? –