对于这个程序,我必须从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
}
}
}
这是我的插入功能。这是&#34; SortedLinkList.h&#34; 该类是模板化的,并且已经提供了一个Node.h类, 它已经有getData()和getNext()函数。变量current,head,previous和count都已声明。 &#34; node.h&#34;文件在&#34; SortedLinkList.h&#34;。
中是#includedtemplate <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++;
}
答案 0 :(得分:0)
以下几行显示您错误地添加了类型SortedLinkList*
。
SortedLinkList* current = head;
SortedLinkList* previous = 0;
您已在函数开头声明了current
和previous
:
Node<T> *newNode, *current, *previous;
也许您打算使用:
current = head;
previous = 0;
您发布的错误对应于以下行:
infile >> sll;
看看你在做什么,你可以删除那一行。