I am trying to construct a linked list that contains string pointers. Since strings can be quite large, I am trying to save space and access time by storing pointers to them in the linked list. The strings are read from a text file and inserted into a linked list.
However, my insert function creates all nodes with pointers to a single memory address, so that all nodes contain a pointer to the same data. I am sure there must a relatively easy fix for this, but I can't seem to find it.
Please help!
Relevant code:
//node struct
struct sNode
{
string * data;
sNode * next;
};
//class definition
class stringList
{
private:
sNode * head;
sNode * tail;
int size;
public:
stringList();
~stringList();
bool listEmpty();
void insertItem(string );
int getPosition (sNode *);
void deleteItem(int );
//functions relevant to insert operation
void stringList::insertItem (string s)
{
if (listEmpty())
{
head=new sNode;
head->next=NULL;
head->data=&s;
tail=head;
}
else
{
sNode * temp = new sNode;
temp->data= &s;
temp->next=NULL;
tail=tail->next;
}
size++;
}
//client function to read from file
stringList s;
void readInput(ifstream & i)
{
string lineread;
while(std::getline(i, lineread))
{
s.insertItem(lineread);
}
}