C++单链表实现多项式相加

源代码:希望对大家有帮助

#include <iostream>
using namespace std ;
//定义结点 
typedef struct CreatePolynomial{
	double coefficient ;
	double index ;
	struct CreatePolynomial *next ;
} Polynomial;
//链表的创建 
Polynomial* createPoly(int n){
	//创建头节点
	Polynomial *head = new Polynomial ;
	Polynomial *pre = head ;
	for(int i = 0 ; i < n ; i++){
		//创建新节点 
		Polynomial *poly = new Polynomial ;
		//为节点赋值
		cout<<"请输入第"<<i+1<<"项的系数和指数:";
		//默认输入的指数从小到大排列 
		cin>>poly->coefficient ; 
		cin>>poly->index ;
		pre->next = poly ;
		pre = poly ;
		poly->next = NULL ;
	}	
	return head ; 
} 
//计算结点个数(除头节点之外)
int lengthPolynomial(Polynomial *head){
	Polynomial *p = new Polynomial ;
	int count  = 0;
	p = head->next ;
	while(p!=NULL){
		count++ ;
		p = p->next ;
	}
	return count ; 
} 
//两个多项式的相加
Polynomial *addpolylist(Polynomial *poly1,Polynomial *poly2)//polynomial:多项式
{
    int temp ;
    Polynomial *first , *second , *third ;
    //将多项式的和存在第一个多项式里面 ,所以最终返回的是第一个多项式的头结点; 
    first = poly1->next ;
    second = poly2->next ;
    third = poly1 ;
    while(first && second)
    {
        if(first->index < second->index)
        {
            third->next = first;
            first = first->next;
            third = third->next;
        } 
        else if(first->index == second->index)
        {
            temp = first->coefficient + second->coefficient;
            if(temp)
            {
                first->coefficient = temp ;
                third->next = first ;
                first = first->next ;
                second = second->next ;
                third = third->next ;
            }
            else
            {
                first = first->next ;
                second = second->next ;
            }
        }
        else
        {
            third->next = second ;
            second = second->next ;
            third = third->next ;
        }
    }
    third->next=(first ? first : second) ;
    return poly1;
} 

//输出每个节点的数据域
void display(Polynomial *head){	
	Polynomial *p = head->next; 
	while(p != NULL){
		if(p->next != NULL){
			if(p->next->coefficient<0){
			cout<<p->coefficient<<"x^"<<p->index; 				
			}
			else{
			cout<<p->coefficient<<"x^"<<p->index<<"+"; 
			}
		}
		else{
		cout<<p->coefficient<<"x^"<<p->index<<endl ; 
		
		}
		p = p->next ; 
	}

}
//主函数入口 
int main(){
	Polynomial *poly1 = createPoly(3) ;
	Polynomial *poly2 = createPoly(5) ;
	cout<<"第一个多项式为:"<<endl ; 
	display(poly1) ;	
	cout<<"第二个多项式为:"<<endl ; 
	display(poly2) ;
	Polynomial *poly = addpolylist(poly1 , poly2) ;
	cout<<"多项式相加的结果为:"<<endl ; 
	display(poly) ;
	return 0 ;
	
}

运行结果示例:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值