⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 polyadd.cpp

📁 给定两个多项式P(x)与Q(x)
💻 CPP
字号:
#include<iostream>   
#include<fstream>    
using namespace std;   
ifstream fin("input.txt");
ofstream fout("output.txt");
#define cin fin
#define cout fout  


typedef struct elem{
	int coef;
	int power;
	struct elem *next;
} element;
typedef element * List;

List insert(List list, int coef, int power) {
	List newel,p,q;

	newel=(element *) malloc(sizeof(element));
	newel->coef= coef;
	newel->power=power;
	newel->next=NULL;
	if(list==NULL)
		list=newel;
	else{
		if(list->power<power){
			newel->next=list;
			list=newel;
		}
		else{
			p=list;
			q=list;
			while((p!=NULL)&&(p->power>power)){
				q=p;
				p=p->next;
			}
			q->next=newel;
			newel->next=p;
		}
	}
		
	return list;
}

List polyadd(List list1, List list2) {
	List list=NULL,p=NULL;
	int value;
	do{
		if(list1==NULL){
			while(list2!=NULL){
				list=insert(list,list2->coef,list2->power);
				list2=list2->next;
			}
		}
		else{
			if(list2==NULL){
				while(list1!=NULL){
					list=insert(list,list1->coef,list1->power);
					list1=list1->next;
				}
			}
			else{
				if (list1->power==list2->power){
					value=list1->coef+list2->coef;
					if (value!=0)
					list=insert(list,value,list1->power);
					list1=list1->next;
					list2=list2->next;
				}
				else{
					if (list1->power>list2->power){
						list=insert(list,list1->coef,list1->power);
						list1=list1->next;
					}
					else 
						if(list2->power>list1->power){
						list=insert(list,list2->coef,list2->power);
						list2=list2->next;
					}
				}
			}
		}
	}
	while(!(list1==NULL&&list2==NULL));
	return list;
}

void print_list(List list) {
	List p=list;
	while (p!=NULL)	{
		cout<<"("<<p->coef<<","<<p->power<<")";
		p=p->next;
	}
	cout<<endl;
	return;
}
 

int main()   
{   
    int coef,power,cas=0;
	List list1=NULL,list2=NULL;
	int flag=0;
    while(cin>>coef>>power){
		if (power==-1)
		{
			flag++;
			if (flag==1)
				continue;
		}
		if(coef!=0){
			if(flag==0)
				list1=insert(list1,coef,power);
			else 
				if (flag==1)
					list2=insert(list2,coef,power);
		}
		if(flag==2){
					cout<<"Case "<<++cas<<":"<<endl;
					flag=0;
					print_list(list1);
					print_list(list2);
					List list=polyadd(list1, list2);
					if (list==NULL)
						cout<<"0"<<endl;
					else print_list(list);
					list1=NULL,list2=NULL;
		}
		
	}
    return 0;   
} 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -