For this program, I have to read in a list of names from a txt file and create a new node for each name, then insert the node into a linked list and keep it sorted as new names are read in. I am having difficulty properly reading in the file line by line, and creating a new node and putting the data in. I am very new to linked lists, but the logic seems sound in my insert function, and I think my errors are caused by my syntax.
Here is my main so far:
#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
}
}
}
Here is my insert function. Which is in "SortedLinkList.h"
The class is templated, and a Node.h class has already been provided,
which has the getData() and getNext() function already. The variables current,head,previous, and count have all been declared. The "node.h" file is #included in the "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++;
}
Best Answer
The following lines look like you added the types,
SortedLinkList*
, by mistake.You already have declarations for
current
andprevious
at the beginning of the function:Perhaps you meant to use:
The error you posted corresponds to the line:
Looking at what you are doing, you can just remove that line.