一、实验名称:多项式相加
二、实验学时:4学时
三、实验目的
1.理解单链表的结构特性和基本操作算法;
2.掌握利用单链表实现两个多项式相加算法。
四、实验内容(步骤)
1.创建两个一元多项式;
2.输出一元多项式;
3.实现两个一元多项式相加;
4.输出相加后的一元多项式。
#include<iostream>
using namespace std;
struct list{
double val;
int index;
list *next;
};
void creat(list* head){
list *p,*q;
p=head;
q=nullptr;
while(1){
int val(0),index(0);
cin>>val>>index;
if(val==-1) return;
q=(list*)malloc(sizeof(list));
q->next=nullptr;
q->val=val;
q->index=index;
p->next=q;
p=q;
}
}
void print(list *head){
if(head==nullptr||head->next==nullptr) return;
list *p=head->next;
while(p->next!=nullptr){
printf("%0.3f*X^%d",p->val,p->index);
if(p->val>0) cout<<"+";
p=p->next;
}
printf("%0.3f*X^%d",p->val,p->index);
}
list* sum(list *head1,list *head2){
if(head1->next==nullptr&&head2->next==nullptr) return nullptr;
list *p1_n=head1->next,*p2_n=head2->next,*head3=new list,*p3=head3,*q3=head3;
p3->next=nullptr;
while(p1_n!=nullptr&&p2_n!=nullptr){
if(p1_n->index==p2_n->index){
if(!(p1_n->val+p2_n->val)){
p1_n=p1_n->next;
p2_n=p2_n->next;
}
else{
p3=(struct list*)malloc(sizeof(list));
p3->next=nullptr;
p3->val=p1_n->val+p2_n->val;
p3->index=p1_n->index;
q3->next=p3;
q3=p3;
p1_n=p1_n->next;
p2_n=p2_n->next;
}
}
else if(p1_n->index<p2_n->index){
if(p1_n->val!=0){
p3=(struct list*)malloc(sizeof(list));
p3->next=nullptr;
p3->val=p1_n->val;
p3->index=p1_n->index;
q3->next=p3;
q3=p3;
p1_n=p1_n->next;
}
else {
p1_n=p1_n->next;
}
}
else if(p1_n->index>p2_n->index){
if(p2_n->val!=0){
p3=(struct list*)malloc(sizeof(list));
p3->next=nullptr;
p3->val=p2_n->val;
p3->index=p2_n->index;
q3->next=p3;
q3=p3;
p2_n=p2_n->next;
}
else {
p2_n=p2_n->next;
}
}
}
if(p1_n==nullptr&&p2_n!=nullptr){
p3->next=p2_n;
while(p2_n!=nullptr){
if(p2_n->val==0){
p3->next=p2_n->next;
free(p2_n);
p2_n=p3->next;
}
else {
p3=p3->next;
p2_n=p3->next;
}
}
return head3;
}
else if(p1_n!=nullptr&&p2_n==nullptr){
p3->next=p1_n;
while(p1_n!=nullptr){
if(p1_n->val==0){
p3->next=p1_n->next;
free(p1_n);
p1_n=p3->next;
}
else {
p3=p3->next;
p1_n=p3->next;
}
}
return head3;
}
else return head3;
}
int main(){
while(1){
list *head1;
head1=(struct list*)malloc(sizeof(list));
head1->next=nullptr;
cout<<"输入第一个表达式:";
creat(head1);
list *head2;
head2=(struct list*)malloc(sizeof(list));
head2->next=nullptr;
cout<<"输入第二个表达式:";
creat(head2);
head1=sum(head1,head2);
cout<<"输出合并后的表达式:";
print(head1);
cout<<endl;
system("pause");
}
return 0;
}