请教一个多项式求和的问题
程序代码:
#include <iostream> using namespace std; typedef struct PNode { float coef; int expn; struct PNode *next; } PNode,*Polynomial; void Read(Polynomial &P,int n); void Print(const Polynomial &P); void Init(Polynomial &P); Polynomial Add(const Polynomial &Pa, const Polynomial &Pb); int main() { Polynomial Pa,Pb; Polynomial AddP; int PaLen,PbLen; Init(Pa); Init(Pb); Init(AddP); cin>>PaLen; Read(Pa,PaLen); cin>>PbLen; Read(Pb,PbLen); AddP = Add(Pa,Pb); Print(AddP); return 0; } void Init(Polynomial &P) { P = new PNode; P->next = NULL; } void Read(Polynomial &P, int n) { PNode *Ptr = P; for(int i = 0; i < n; i++) { PNode *Pn = new PNode; cin>>Pn->coef>>Pn->expn; Pn->next = NULL; Ptr->next = Pn; Ptr = Ptr->next; } } void Print(const Polynomial &P) { PNode *Ptr = P->next; while(Ptr) { cout<<Ptr->coef<<" "<<Ptr->expn; if(Ptr->next != NULL) cout<<" "; Ptr = Ptr->next; } } Polynomial Add(const Polynomial &Pa, const Polynomial &Pb) { Polynomial Pc; Init(Pc); PNode *Ptra = Pa->next,*Ptrb = Pb->next, *Ptrc = Pc; while(Ptra && Ptrb) { if(Ptra->expn > Ptrb->expn) { Ptrc->next = Ptra; Ptra = Ptra->next; } else if(Ptra->expn < Ptrb->expn) { Ptrc->next = Ptrb; Ptrb = Ptrb->next; } else { PNode *temp = new PNode; temp->coef = Ptra->coef + Ptrb->coef; temp->expn = Ptra->expn; Ptrc->next = temp; Ptra = Ptra->next; Ptrb = Ptrb->next; } Ptrc = Ptrc->next; } if(Ptra) Ptrc->next = Ptra; else if(Ptrb) Ptrc->next = Ptrb; return Pc; } 问题出在Polynomial Add(const Polynomial &Pa, const Polynomial &Pb);这个函数的else语句中的Ptrc->next = temp;。 当执行完Ptrc->next = temp;这个语句以后,Pb链表的值被篡改了。 我始终想不明白为什么执行这个语句以后Pb的链表值被篡改了。 求大家的帮助。 原问题在这里:https://pta. 补充: 我将: PNode *Ptra = Pa->next,*Ptrb = Pb->next, *Ptrc = Pc; 更改为 const PNode *Ptra = Pa->next,*Ptrb = Pb->next, *Ptrc = Pc; 以后出现如下报错(gcc version 6.3.1): 02.cpp: In function ‘PNode* Add(PNode* const&, PNode* const&)’: 02.cpp:79:20: error: assignment of member ‘PNode::next’ in read-only object Ptrc->next = Ptra; ^~~~ 02.cpp:79:20: error: invalid conversion from ‘const PNode*’ to ‘PNode*’ [-fpermissive] 02.cpp:83:20: error: assignment of member ‘PNode::next’ in read-only object Ptrc->next = Ptrb; ^~~~ 02.cpp:83:20: error: invalid conversion from ‘const PNode*’ to ‘PNode*’ [-fpermissive] 02.cpp:90:20: error: assignment of member ‘PNode::next’ in read-only object Ptrc->next = temp; ^~~~ 02.cpp:96:25: error: assignment of member ‘PNode::next’ in read-only object if(Ptra) Ptrc->next = Ptra; ^~~~ 02.cpp:96:25: error: invalid conversion from ‘const PNode*’ to ‘PNode*’ [-fpermissive] 02.cpp:97:30: error: assignment of member ‘PNode::next’ in read-only object else if(Ptrb) Ptrc->next = Ptrb; ^~~~ 02.cpp:97:30: error: invalid conversion from ‘const PNode*’ to ‘PNode*’ [-fpermissive] 为什么看似赋值的语句会出现如上的报错。
[此贴子已经被作者于2017-4-1 22:56编辑过]