2016-11-17 130 views
-4

所以我有一个问题,当我添加一个新的节点到列表中时,我的头节点发生了变化。我必须从文件中读取多行。每条线将成为函数f(x)= ...并且节点是函数中的奇异表达式,因此节点1例如可以是25x^2并且节点2可以是15x。所以我的Node类保存系数,所以对于节点1它将是25,并且指数x到达。这是导致我认为的问题的代码段。C++链接列表

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(节点* 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

插入节点对每一行的代码也可以简化如下所述,因为if-else条件的两个陈述是相同的。 Node* n的变量需要在while-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); 
    } 
} 
+0

感谢您在改进我的代码方面的帮助。我一定会仔细研究一下。但我发现了这个问题。我的问题措辞不佳,但基本上我只创建了一个节点,并试图将同一节点添加到列表中,但每次都使用不同的值。我用nodeList.insertNode(new Node(coef,exp,NULL))替换了nodeList.insertNode(n);这一行,而不是Node * n。 – CMW

+0

欢迎您。我太关注代码的简化了,只是简单地将代码'Node * n = new Node;'放在while循环中,没有任何解释或评论。因此,我不直接回答你的问题。 – Kai