链表实现多项式乘法

为了实现方便,这里默认多项式项数据是按照指数递增的顺序输入的,默认两多项式相乘后最大的指数小于1000

#include <iostream>
#include <cmath>
using namespace std;
struct Node{
	float cofe;
	int exp;
    Node *next;
    Node(float c,int e,Node *ne=NULL){
    	cofe=c;
    	exp=e;
    	next=ne;
	}
	Node *InsertAfter(float c,int e);
	friend ostream& operator<<(ostream&,const Node&);
};
Node *Node::InsertAfter(float c,int e){
	next=new Node(c,e);
	return next;
}
std::ostream& operator<<(ostream& out,Node& x){
	if(x.cofe==0)return out;
	out<<x.cofe;
	switch(x.exp){
		case 0:break;
		case 1:out<<"X";break;
		default:out<<"X^"<<x.exp;break;
	}
	return out;
}
int main(){
	Node *p;
	Node *q;
	Node first(0,-1);
	Node first2(0,-1);
	p=&first;
	q=&first2;
	int N;//输入多项式有多少项
	int M;
	cin>>N;
	float inputc;
	int inpute;
	int maxorder1,maxorder2;
	for(int i=0;i<N;i++){
		cin>>inputc>>inpute;
		if(i==N-1){
			maxorder1=inpute;
		}
		p=p->InsertAfter(inputc,inpute);
	} 
	cin>>M;//输入第二个多项式有多少项 
	for(int i=0;i<M;i++){
		cin>>inputc>>inpute;
		if(i==M-1){
			maxorder2=inpute;
		}
		q=q->InsertAfter(inputc,inpute);
	}
	p=first.next;
	q=first2.next;
	Node result(0,-1);
	Node *r=&result;
	if(maxorder1!=-1||maxorder2!=-1){
		int maxorder=maxorder1+maxorder2;//计算出最大指数
		for(int i=0;i<=maxorder;i++){
			r=r->InsertAfter(0,i);
		}
		int temp[1000];
		for(int i=0;i<1000;i++){
			temp[i]=0;
		}
		while(p!=NULL){
			q=first2.next;
			while(q!=NULL){
				int tempc=p->cofe*q->cofe;
				int tempe=p->exp+q->exp;
				temp[tempe]+=tempc;
				q=q->next;
			}
			p=p->next;
		}
		r=result.next;
		for(int i=0;i<=maxorder;i++){
			r->cofe+=temp[i];
			r=r->next;
		}
	}
	r=result.next;
	while(r!=NULL){
		if(r->cofe!=0){
			std::cout<<*r;
		    if(r->next!=NULL){
			    if(r->next->cofe>0){
				cout<<"+";
			    }
		    }
		}
		r=r->next;
	}
	return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值