链表缺少节点并在打印时颠倒顺序

Linked List is missing out nodes and reversing order when printing

本文关键字:顺序 打印 节点 链表      更新时间:2023-10-16

我正在创建一个基本程序,该程序使用链表和文本文件(以填充链表(对数据执行一些操作。

我已经设置了一个我认为是工作链表结构和一种"有效"但可能效率低下的方式来读取文本文件并将数据放入链表节点。

当我读取文件时,我会检查正在读取的内容是否正确(通过输出到屏幕(,然后使用我创建的 insertNode 函数。

但是,当我去打印链表 I 时,一些节点不是正在读取的数据,并且打印的顺序是相反的?

我的程序非常大,所以我只包含相关功能(我已经编辑到基本功能(和文本文件/输出。


文本文件:

car,Ferarri,12.0,aa,3,1,1,true
car,Mercedes,8.0,bb,5,4,0,false

打印时的链接列表:

car -6.27744e_066 8.0 -842150451 5 4 false
car -6.27744e_066 12.0 -842150451 3 1 true

它几乎打印了正确的输出,但顺序相反,字符串显示为负整数,并且缺少 maxLoad 节点。谁能明白为什么?


读取文件

void readFile()
{
string text;
string temp; // Added this line
node* newNode = new node;
ifstream file;
file.open("example.txt");
for (int i = 0; i < 2; i++)
{
getline(file, temp);
text = temp;
string input = text;
istringstream ss(input);
string token;
node* newNode = new node;
int counter = 0;
while (getline(ss, token, ','))
{
cout << token << 'n';
newNode->rented = token;
counter++;
if (counter == 0)
{
newNode->make = token;
}
else if (counter == 1)
{
newNode->model = token;
}
else if (counter == 2)
{
std::istringstream ss(token);
ss >> newNode->engine;
}
else if (counter == 3)
{
newNode->registration = token;
}
else if (counter == 4)
{
std::istringstream ss(token);
ss >> newNode->doors;
}
else if (counter == 5)
{
std::istringstream ss(token);
ss >> newNode->passengers;
}
else if (counter == 6)
{
std::istringstream ss(token);
ss >> newNode->maxload;
}
else
{
newNode->rented = token;
}
}
list.insertNode(newNode);
}
file.close();
}

插入节点

void linkedList::insertNode(node* newNode)
{
newNode->nextNode = head;
head = newNode;
}

打印列表

void linkedList::displayList()
{
node* thisNode = head;
do
{
cout << thisNode->make << "t";
cout << thisNode->model << "t";
cout << thisNode->engine << "t";
cout << thisNode->registration << "t";
cout << thisNode->doors << "t";
cout << thisNode->passengers << "t";
cout << thisNode->maxload << "t";
cout << thisNode->rented << "t";
cout << "nt";
thisNode = thisNode->nextNode;
} while (thisNode != NULL);
}

在读取循环之外,只分配一次新节点。确保每次插入时都分配一个新的。此外,您将在列表的头部而不是尾部插入新元素 - 因此顺序相反。

这里有一些可以帮助您的东西:

node dummy;
dummy.next = nullptr;
node* tail = &dummy;
while (getline(...))
{
node* newNode = new node();
// fill in data
tail->next = newNode;
tail = newNode;
}
// list.head = dummy.next;