对于这个程序,我必须从 txt 文件中读取名称列表,并为每个名称创建一个新节点,然后将该节点插入到链表中,并在读入新名称时保持其排序。我遇到了困难正确地逐行读取文件,然后创建一个新节点并将数据放入。我对链表非常陌生,但我的插入函数中的逻辑似乎很合理,我认为我的错误是由我的语法引起的。 到目前为止,这是我的主要内容:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "SortedLinkList.h"
using namespace std;
int main()
{
SortedLinkList<string> sll; //create sortedlinklist object
SortedLinkList<string> sll2;
ifstream infile("List1.txt");
if(infile.fail()) {
cout << "the input file could not be opened" << endl;
exit(0);
}
else {
cout << "Opening file 1" << endl;
string s;
while (infile >> s)
{
infile >> sll;
sll.insert(s); //attempting to create new node and use data read
from file
}
}
}
这是我的插入功能。它位于“SortedLinkList.h”中 该类是模板化的,并且已经提供了 Node.h 类, 其中已经有 getData() 和 getNext() 函数。变量 current、head、previous 和 count 均已声明。 “node.h”文件#included 在“SortedLinkList.h”中。
template <class T>
void SortedLinkList<T>::insert(const T & value)
{
cout << "insert data" << endl;
//allocate a node with new
Node<T> *newNode, *current, *previous;
newNode = new Node<T>(value);
current = head;
previous = 0;
while(current != NULL)
if(head == 0)
{
head = newNode;
}
else
{
SortedLinkList* current = head;
SortedLinkList* previous = 0;
//traverse list to find ins. location
while(current != 0)
{
if(current->getData() >= newNode->getData())
{
break;
}
else
{
previous = current;
current = current->getNext();
}
}
//insert at head
if(current == head)
{
newNode->getNext() = head;
head = newNode;
}
//insert after head
else
{
newNode->getNext() = current;
previous->getNext() = newNode;
}
}
count++;
}
以下几行看起来像是您错误地添加了类型,
SortedLinkList*
。
SortedLinkList* current = head;
SortedLinkList* previous = 0;
您已经在函数开头声明了
current
和 previous
:
Node<T> *newNode, *current, *previous;
也许你想使用:
current = head;
previous = 0;
您发布的错误对应于以下行:
infile >> sll;
看看你在做什么,你可以删除该行。