所以,嘿,我有這個項目我有一個問題。我應該從文件中讀取整數並將它們插入到列表中。有一個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
請重新格式化並重新合適您的代碼。你不想讓自己的代碼儘可能理解和可讀嗎?讓別人更容易看到你做了什麼,以及問題出在哪裏? –