带有类的C ++链表

时间:2016-11-17 02:07:38

标签: c++

因此,当我向列表中添加新节点时,我的头节点发生了变化。我必须从文件中读取多行。每一行将是函数f(x)= ...并且节点是函数中的单数表达式,因此节点1例如可以是25x ^ 2并且节点2可以是15x。所以我的Node类保存系数,因此对于节点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);
}

}

这是我的List :: insertNode(Node * n)类:

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->getExp() == n->getExp()){
            likeTerms = true;
            break;
        }
        ptr = ptr->getNext();
    }
    //If they aren't like terms, just add the node to the end.
    if (!likeTerms){
        ptr = head;
        while(ptr->getNext() != NULL)
        {
            ptr = ptr->getNext(); //traverses to the last node in list.
        }
        ptr->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->setCoef(ptr->getCoef()+n->getCoef());
}

}

1 个答案:

答案 0 :(得分:-1)

为每行插入节点的代码也可以简化如下,因为if-else条件的两个语句是等价的。需要在Node* nwhile-loop中创建nodeList的变量只包含一个节点,其中包含函数f(x)的最后一项。

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)也可以简化。以下是简化版本。

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);
    }
}