有兩個指數遞減的一元多項式,寫一程序先求這兩個多項式的和,再求它們的積。
【提示】 用帶表頭結點的單鏈表作為多項式的存儲表示;要建立兩個單鏈表;多項式相加就是要把一個單鏈表中的結點插入到另一個單鏈表中去,要注意插入、刪除操作中指針的正確修改。
#include<iostream> #include<cmath> using namespace std; /** 數據結構習題1 多項式的相加和相乘 @劉輝 **/ struct Node{ int data; int index; Node* next; }; Node *insertList(Node* head,Node* p); //插入鏈表 Node *createList(); //創建鏈表 void printList(Node *head); //打印鏈表 Node *addList(Node *p1,Node *p2); //實現加法運算 Node *createList() { int index,data; Node *p,*head,*q; head = new Node; p = head; cout<<"請輸入要輸入的多項式a的冪指數:"; cin>>index; cout<<"請輸入該指數的參數:"; cin>>data; while(index!=0) { q = new Node; q->index = index; q->data = data; p->next = q; p = q; cout<<"請輸入要輸入的多項式a的冪指數:"; cin>>index; cout<<"請輸入該指數的參數:"; cin>>data; } p->next = NULL; return head; } //多項式相加 Node *addList(Node *p1,Node *p2) { int add; Node *temp,*head,*p3; p1 = p1->next; p2 = p2->next; head = temp = new Node; head->next = NULL; while(p1&&p2) { if(p1->index==p2->index) { add = p2->data + p1->data; if(add!=0) { p3 = new Node; p3->index = p2->index; p3->data = add; p3->next = NULL; } p1 = p1->next; p2 = p2->next; } else if(p1->index<p2->index) { p3 = new Node; p3->data = p2->data; p3->index = p2->index; p3->next = NULL; p2 = p2->next; } else { p3 = new Node; p3->data = p1->data; p3->index = p1->index; p3->next = NULL; p1 = p1->next; } if(head->next ==NULL) { head->next = p3; temp = p3; } else { temp->next = p3; temp = p3; } } temp->next = p1?p1:p2; return head; } //多項式相乘 Node* mulList(Node *p1,Node *p2) { Node *head,*temp,*s,*r,*q; head = new Node; head->next = NULL; temp = new Node; temp->next = NULL; p1 = p1->next; p2 = p2->next; for(s=p1;s;s=s->next) { for(r=p2;r;r=r->next) { q = new Node; temp->next = q; q->data = s->data * r->data; q->index = s->index + r->index; q->next = NULL; head = addList(temp,head); } } return head; } //打印多項式 void printList(Node *head) { Node *p = NULL; p = head->next; if(p==NULL) { cout<<"文件為空"; } else { do { if(p->data>=0) cout<<p->data<<"x^"<<p->index; else cout<<p->data<<"x^"<<p->index; if(p->next!=NULL) cout<<"+"; p=p->next; }while(p != NULL); cout<<endl; } } //主函數 int main() { int i; Node *p1=NULL,*p2=NULL,*p3=NULL,*p4=NULL; cout<<"創建第一個多項式的鏈表:"<<"\n"; p1 = createList(); cout<<"\n"; cout<<"創建第二個多項式的鏈表:"<<"\n"; p2 = createList(); cout<<"第一個多項式為:"; printList(p1); cout<<"\n"<<"第二個多項式為:"; printList(p2); p3 = addList(p1,p2); //實現多項式相加 cout<<"\n"<<"多項式相加後為:"; printList(p3); cout<<endl; p4 = mulList(p1,p2); //實現多項式相乘 cout<<"多項式相乘後為:"; printList(p4); cin>>i; return 0; }