所以当我插入到我的链表中并使用最高指数排序时,我无法让我的代码添加系数值。例如,这是我的输出:
(x^6) + (5x^6) + (3x^2) + (6x^2) + (-1) [end of polynomial]
(2x^7) + (5x^7) + (2x^5) + (4x^2) + [end of polynomial]
他们应该在哪里:
(6x^6) + (9x^2) + (-1)
(7x^7) + (5x^7) + (2x^5) + (4x^2)
这是我用来查找插入点的代码,以及列表插入函数。
Node* findSpot (int coefficient, int exponent)
{
//Node *Spot = new Node (coefficient, exponent);
Node *spot = listHead;
while(spot->next != NULL && spot->next->exponent > exponent)
{
spot = spot->next;
}
/*if (spot->exponent == exponent)
{
return spot;
}*/
return spot;
}
//Function to insert into the linked list
void listInsert(int coefficient, int exponent)
{
Node *spot = findSpot (coefficient, exponent);
/*if(spot->exponent == exponent)
{
int temp;
temp = spot->coefficient + coefficient;
//Node *newNode = new Node (temp, exponent);
spot->coefficient = spot->coefficient + coefficient;
//Node * newNode = new Node (temp, exponent);
//newNode->next = spot->next;
//spot->next = newNode->next;
//spot = newNode;
}*/
Node* newNode = new Node(coefficient, exponent);
newNode->next = spot->next;
spot->next = newNode;
}
我不确定如何更改它以便它取代节点。如果我更改指针,我可能还必须为节点创建一个前一个指针,这似乎真的很烦人。我在listInsert函数中注释了一堆我试图做的事情,如果指数是相同的,那么系数可以添加,但它们似乎都不适用于当前的实现。