C++ C++;带类的链表

C++ C++;带类的链表,c++,C++,因此,当我向列表中添加新节点时,我的头部节点发生了变化。我必须从一个文件中读取多行内容。每一行都是一个函数f(x)=。。。节点是函数中的奇异表达式,因此,例如,节点1可以是25x^2,节点2可以是15x。所以我的节点类保存了系数,所以对于节点1,它将是25,指数x变为。下面是我认为导致问题的代码片段 Node* n = new Node(); List nodeList; nodeList.setHead(NULL); while(not at the end of line) { //Thi

因此,当我向列表中添加新节点时,我的头部节点发生了变化。我必须从一个文件中读取多行内容。每一行都是一个函数f(x)=。。。节点是函数中的奇异表达式,因此,例如,节点1可以是25x^2,节点2可以是15x。所以我的节点类保存了系数,所以对于节点1,它将是25,指数x变为。下面是我认为导致问题的代码片段

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->setCoef(coef);
    n->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->setCoef(coef);
    n->setExp(exp);
    nodeList.insertNode(n);
}
}

以下是我的列表::insertNode(Node*n)类:


}由于
if else
条件的两个语句是等效的,因此每行插入节点的代码也可以简化如下。需要在
while循环
中创建
节点*n
的变量,或者
节点列表
将只包含一个节点,其中包含函数f(x)的最后一项

函数
void List::insertNode(Node*n)
也可以简化。以下是简化版本

void List::insertNode(Node* n) {
    Node* ptr  = header;
    Node* prev = NULL;
    bool  same_exp_occurred = false;
    while (ptr) {
        if (n->getExp() == ptr->getExp()) {
            ptr->setCoef(ptr->getCoef()+n->getCoef());
            same_exp_occurred = true;
            break;
        }
        prev = ptr;
        ptr  = ptr->getNext();
    }

    if (!same_exp_occurred && prev) {
        prev->setNext(n);
    }
}

感谢您帮助我改进代码。我一定会看的。不过我发现了问题。我对这个问题的措辞很糟糕,但基本上我只创建了一个节点,每次都试图将同一个节点添加到列表中,但值不同。我没有使用Node*n,而是替换了nodeList.insertNode(n);,使用nodeList.insertNode(新节点(coef,exp,NULL));欢迎光临。我太专注于代码的简化,只是简单地把代码
Node*n=newnode在while循环中,没有任何解释或注释。因此,我没有直接回答你的问题。
while (not at the end of line)
{
    Node* n = new Node;
    n->setCoef(coef);
    n->setExp(exp);
    nodeList.insertNode(n);
}
void List::insertNode(Node* n) {
    Node* ptr  = header;
    Node* prev = NULL;
    bool  same_exp_occurred = false;
    while (ptr) {
        if (n->getExp() == ptr->getExp()) {
            ptr->setCoef(ptr->getCoef()+n->getCoef());
            same_exp_occurred = true;
            break;
        }
        prev = ptr;
        ptr  = ptr->getNext();
    }

    if (!same_exp_occurred && prev) {
        prev->setNext(n);
    }
}