#include<iostream> using namespace std; //以下所有参数使用const较为好 struct node { double coef = 0; int exp = 0; node* next = NULL; }; node* Attach(node* position, double x, int y) { node* temp = new node; temp->coef = x; temp->exp = y; position->next = temp; return temp; } node* add(node* head1,node* head2) { node* p = head1->next; node* q = head2->next; node* temp1 = new node; node* temp2 = temp1; while (p != NULL&&q != NULL) { if (p->exp == q->exp) { temp1 = Attach(temp1, p->coef + q->coef, p->exp); p = p->next; q = q->next; } else { if (p->exp > q->exp) { temp1 = Attach(temp1, q->coef, q->exp); q = q->next; } else { temp1 = Attach(temp1, p->coef, p->exp); p = p->next; } } } while (p != NULL) { temp1 = Attach(temp1, p->coef, p->exp); p = p->next; } while (q != NULL) { temp1 = Attach(temp1, q->coef, q->exp); q = q->next; } return temp2; } node* multipyaid( node *head, node *temp)//记着head不能变 { node* a = head->next; node* ans = new node; node* c = ans; while (a != NULL) { node *b = new node; b->coef = a->coef*temp->coef; b->exp = a->exp + temp->exp; c->next = b; c = c->next; a = a->next; } return ans; } node* multipy(node* head1,node* head2)//记着head1,head2不能变 { node* temp1; node* temp2 = new node; node* temp3 = new node; temp1 = head2->next; while (temp1 != NULL) { temp2 = multipyaid(head1, temp1); temp3 = add(temp3, temp2); temp1 = temp1->next; } return temp3; } int main() { node* a = new node; node* b = a; a=Attach(a, 1, 2); a=Attach(a, 2, 3); a=Attach(a, 3, 4); a = b->next; while (a != NULL) { cout << a->coef << " " << a->exp << endl; a = a->next; } node* c = new node; node* d = c; c = Attach(c, 1, 2); c = Attach(c, 2, 3); c = Attach(c, 3, 4); c = d->next; while (c != NULL) { cout << c->coef << " " << c->exp << endl; c = c->next; } node* e = multipy(b, d); node* f = e->next; while (f != NULL) { cout << f->coef << " " << f->exp << endl; f = f->next; } system("pause"); return 0; }
线性表求解多项式
猜你喜欢
转载自blog.csdn.net/qq_36921652/article/details/79482066
今日推荐
周排行