正在从文件中读取中的数据并插入到链表C++中

Reading data in from file and inserting into Linked List C++

本文关键字:插入 C++ 链表 数据 文件 读取      更新时间:2023-10-16

对于这个程序,我必须从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、previor和count都已声明。"node.h"文件#包含在"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;

在函数的开头已经有了currentprevious的声明:

Node<T> *newNode, *current, *previous;

也许你打算使用:

    current = head;
    previous = 0;

您发布的错误对应于以下行:

        infile >> sll;

看看你在做什么,你可以去掉那条线。