Home > Back-end >  One yuan polynomial addition has tips section of wrong don't know how to change QAQ
One yuan polynomial addition has tips section of wrong don't know how to change QAQ

Time:09-21

This is the topic of dry
subject description
A one yuan polynomial can be thought of by one yuan several monomial sorted by decreasing powers into a linear list, please write a program to input two unary polynomial summation, and output the result of the sum,
Enter
Input into two one yuan polynomial, each one yuan polynomial input line, according to drop power input in turn each monomial coefficient and index, and at the end, 1-1 - coefficient and index are integers, index of not less than zero,
O
Output for polynomial summation result, according to the drop coefficient and index of power output, in turn, each single numerical behind each separated by a space, the output polynomial, a new line after monomial may output coefficient 0 - unless the polynomial is 0, then directly 0,
The sample input Copy
12 1 2 7 3 5 6 0-1-1
7 5 September 4 3 0-1-1
Sample output Copy
2 7 to 10 5 September 4 12 1 9 0


The following is my solution in the debug process in the Add function segment where the fault is wrong about how to change
By the way this kind of mistake later how to avoid error do list several times recently,
 # include 
using namespace std;
Typedef struct PNode {
Int coef.
Int expon;
Struct PNode * next;
} PNode, * Polynomial;
Void CreatePoly (Polynomial & amp; P) {
P=new PNode;
P - & gt; Next=NULL;
Polynomial q, r,
R=p;
While (1) {
Q=new PNode;
Q - & gt; Next=NULL;
cin> Q - & gt; Coef> Q - & gt; Expon;
If (q - & gt; Coef==1 & amp; & Q - & gt; Expon==1) break;
R - & gt; Next=q;
R=q;
}
delete q;
}
Void PrintPoly (Polynomial p) {
Polynomial q;
Q=p - & gt; next;
While (q) {
Printf (" % d % d ", q - & gt; Coef, q - & gt; Expon);
Q=q - & gt; next;
}
printf("\n");
}
Void the Add (Polynomial & amp; Pa, Polynomial & amp; Pb) {
Polynomial p1, p2, p3, temp1, temp2; P1=pa - & gt; next; The p2=pb - & gt; next; P3=pa;
int sum=0;
While (p1 & amp; & P2) {
If (p1 - & gt; Expon==p2 - & gt; Expon) {
Sum=p1 - & gt; Coef + p2 - & gt; Coef.
If (sum==0) {
Temp1=p; Temp2=p2;
P1=p1 - & gt; next; The p2=p2 - & gt; next;
Pa - & gt; Next=p; Pb - & gt; Next=p2;
The delete temp1; The delete temp2;
}
If (sum!=0) {
P1 - & gt; Coef=sum;
P3 - & gt; Next=p; P3=p; P1=p1 - & gt; next;
Temp2=p2; The p2=p2 - & gt; next; Pb - & gt; Next=p2; The delete temp2;
}
}
If (p1 - & gt; Expon!=p2 - & gt; Expon) {
If (p1 - & gt; Expon> The p2 - & gt; Expon) {
P3 - & gt; Next=p;
P3=p;
P1=p1 - & gt; next;
}
The else {
P3 - & gt; Next=p2;
P3=p2;
The p2=p2 - & gt; next;
}
}
}
P3 - & gt; Next=p1? P1, p2,
//if (p1) {
//p3 - & gt; Next=p;
//}
//if (p2) {
//p3 - & gt; Next=p2;
//}
The delete pb;
PrintPoly (pa);
}
Int main () {
Polynomial p1, p2,
CreatePoly (p1);
//PrintPoly (p1);
CreatePoly (p2);
//PrintPoly (p2);
Add (p1, p2);
}
  • Related