2016-11-17 232 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