C++ linked list with classes
<p>So I have a problem with my head node changing when I add a new node to the list. I have to read in multiple lines from a file. Each line is going to be a function f(x) = ... and the nodes are singular expressions in the function so node 1 for example can be 25x^2 and node 2 could be 15x. So my Node class holds the coefficient so for node 1 it would be 25, and the exponent x goes to. Here's the pieces of code that are causing the problem I think.</p>

<pre><code>Node* n = new Node();
List nodeList;
nodeList.setHead(NULL);

while(not at the end of line)
{
//This while loop just inputs from file, and stores values into Node class.
if(!nodeList.getHead()) //so this is first node being input.
{
    //i collect the values for coefficient and exponent here...
    n-&gt;setCoef(coef);
    n-&gt;setExp(exp);
    nodeList.insertNode(n);
}
else //so this is not the first node in the list.
{
    //i collect the values for coefficient and exponent again here...
    //After this code below, the head node changes to n's coef and exp.
    //I know this is because n is still pointing at the head node
    //but I keep getting runtime errors when trying to fix this.
    n-&gt;setCoef(coef);
    n-&gt;setExp(exp);
    nodeList.insertNode(n);
}
</code></pre>

<p>}</p>

<p>Here is my List::insertNode(Node* n) class: </p>

<pre><code>void List::insertNode(Node* n){
//if theres no head node, just set it to the n node and continue.
if (!head)
    head = n;
else{
    Node* ptr = head; //used to traverse through list.
    bool likeTerms = false;
    while(ptr) //This while loop checks to make sure theres no like terms.
    {
        if (ptr-&gt;getExp() == n-&gt;getExp()){
            likeTerms = true;
            break;
        }
        ptr = ptr-&gt;getNext();
    }
    //If they aren't like terms, just add the node to the end.
    if (!likeTerms){
        ptr = head;
        while(ptr-&gt;getNext() != NULL)
        {
            ptr = ptr-&gt;getNext(); //traverses to the last node in list.
        }
        ptr-&gt;setNext(n); //Adds the new node to the spot after the last node
    }
    else if (likeTerms == true)//If the x exponents have like terms, 
                               //then just combine them.
        ptr-&gt;setCoef(ptr-&gt;getCoef()+n-&gt;getCoef());
}
</code></pre>

<p>}</p>