#ifndef POLYON_H_INCLUDED #define POLYON_H_INCLUDED
//polyon.h #include <iostream> using namespace std; class node { public: int pa; int times; node *next; node(int p = 0,int t = 0,node* n=NULL) { pa = p; times = t; next = n; } }; class polynomial { private: void swap(node *n1,node *n2) { int n,m; n=n1->pa;n1->pa=n2->pa;n2->pa=n; m=n2->times;n2->times=n1->times;n1->times=m; } public: node *head; node *curr; int size; polynomial() { head = curr =new node(); size =0; } polynomial(polynomial &p1,polynomial &p2) { p1.curr = p1.head; while(p1.curr->next!=NULL) p1.curr=p1.curr->next; p1.curr->next = p2.head->next; delete p2.head; head = p1.head; curr = p1.head; size = p1.size+p2.size; } void insert(int p,int t) { curr =new node(p,t,head->next); head->next = curr; size++; } void sort() { for(int i =0;i<size;i++){ for(curr=head->next;curr->next!=NULL;curr=curr->next) { if(curr->times < curr->next->times) swap(curr,curr->next); }} } void merge() { node *tmp; for(curr =head->next;curr!=NULL;curr=curr->next) { // cout<<"#1"<<endl; tmp=curr; while(tmp->next!=NULL) { //cout<<"#2"<<endl; if(tmp->next->times==curr->times) { curr->pa += tmp->next->pa; node *t=tmp->next; tmp->next=tmp->next->next; delete t; } else{ tmp=tmp->next;} } } } void print() { sort(); merge(); // cout<<"merge complete"<<endl; sort(); // cout<<"print"<<endl; curr = head->next; while(curr!=NULL) { if(curr->pa!=0&&curr->next!=NULL) cout<<curr->pa<<'x'<<'^'<<curr->times<<'+'; if(curr->next==NULL) cout<<curr->pa<<'x'<<'^'<<curr->times; curr=curr->next; } cout<<endl; } }; #endif // POLYON_H_INCLUDED
就是定义了一个用于储存多项式的函数;
//main function //author: byshen #include <iostream> #include "polyon.h" using namespace std; int main() { int a,b; char c; polynomial y1,y2; do { cout<<"input the coefficient and exponent of y1: "; cin>>a>>b; y1.insert(a,b); cout<<"continue?(n' to quit)";cin>>c; } while(c!='n'); cout<<"y1 = "; y1.print(); do { cout<<"input the coefficient and exponent of y2: "; cin>>a>>b; y2.insert(a,b); cout<<"continue?(n' to quit)";cin>>c; } while(c!='n'); cout<<"y2 = "; y2.print(); polynomial result(y1,y2); cout<<"result = "; result.print(); return 0; }
感谢自己又坚持了一天!
加油!