#include <iostream>
using namespace Std;
Class poly{
Public
int Coef;
int expon;
Poly *next;
};
Poly*input (); Input function
Poly *polyadd (poly *p1, poly *p2); Add function
Poly *attach (poly*rear, int coef, int expon); Link function
int compare (int a, int b); Size comparison function
int main ()
{
cout << "Please enter polynomial P1:" << Endl;
POLY*P1 = input ();
cout << "Please enter polynomial P2:" << Endl;
POLY*P2 = input ();
POLY*P3 = Polyadd (P1, p2);
cout << "p1+p2 after:" << Endl;
while (p3) {
cout << p3->coef << ' << p3->expon << Endl; Output results
P3 = p3->next;
}
return 0;
}
Poly*input ()
{
Poly*p = new Poly;
Poly*head = p, *p1 = p;
cout << "Please enter a coefficient and an exponent to end with a factor of 0;" << Endl;
CIN >> P->coef >> p->expon;
if (P->coef = = 0) {
Head->next =null;
return head;
}
while (P->COEF) {
P1 = p;
p = new Poly;
CIN >> P->coef >> p->expon;
P1->next = p;
}
Delete p;
P1->next = NULL;
return head;
}
Poly *polyadd (poly *p1, poly *p2)
{
int sum;
Poly*p = new Poly;
Poly*head = P,*rear = P;
while (P1&&P2) {
Switch (compare (P1->expon, p2->expon)) {//each time you compare the P1 and P2 indices
Case 1:
Rear=attach (rear, P1->COEF, p1->expon); Each cycle is replaced with an open point
P1 = p1->next; Move down one node.
Break
Case-1:
Rear=attach (rear, P2->COEF, p2->expon);
P2 = p2->next; Move down one node.
Break
Case 0:
sum = P1->coef + p2->coef;
if (sum)//if the coefficient is not 0
Rear=attach (rear, sum, p1->expon);
P1 = p1->next;
P2 = p2->next;
Break
}
}
while (p1) {//jumps above the result either P1 is empty or P2 is empty
Rear=attach (rear, P1->COEF, p1->expon);
P1 = p1->next;
}
while (p2) {
Rear=attach (rear, P2->COEF, p2->expon);
P2 = p2->next;
}
Rear->next = NULL; The next pointer to the open point points to an empty
Poly*temp = head;
Head = head->next;
Delete temp; To delete an empty head node
return head; Returns the head node.
}
Poly *attach (poly *rear,int sum, int expon)
{
Poly*p = new Poly;
P->coef = sum;
P->expon = Expon;
Rear->next = p; Connect the results together
return p;
}
int compare (int a, int b)
{
if (a > B)
return 1;
else if (a = = b)
return 0;
return-1;
}
polynomial addition (linked list)