c++ 链表实现多项式加法

题目要求:

1、请使用链表实现两个多项式的加法运算,其中多项式的项按指数从高到低排列。例如,输入形式为3 2 -1 1 2 0

测试样例:

样例1:

输入样例:

3 4 2 3 1 2(第一个多项式)

-2 3 4 2 5 1 6 0(第二个多项式)

输出样例:

3 4 5 2 5 1 6 0求和结果)


代码实现:

//链表
#include <iostream>
using namespace std;


//类定义
class lianbiao		
{
private:
	int zhen_de_shu_ju;		//zhen_de_shu_ju 数据
	int zuo_biao;		//zuo_biao 坐标
	class lianbiao* next;

public:
	lianbiao()	//构造函数
	{
		zhen_de_shu_ju =zuo_biao = 0;	
		next = nullptr;		
	}

	~lianbiao()	//析构函数
	{
		zhen_de_shu_ju = zuo_biao = 0;
		next = nullptr;
	}
	void add(lianbiao n3, lianbiao n4);	//多项式相加函数
	void input();	//输入
	void output( );	//输出
	void shoudong();	//手动析构
};

//函数定义
void lianbiao::add(lianbiao n1, lianbiao n2)	//多项式相加函数
{
	lianbiao* current1, * current2;
	lianbiao *current3=new lianbiao;
	
	current1 = n1.next;
	current2 = n2.next;
	next=current3 ;
	while (current1 != NULL && current2 != NULL)
	{
		if ((current1->zuo_biao) > (current2->zuo_biao))
		{
			current3 ->next= current1;
			current3 = current3->next;
			current1 = current1->next;			
		}
		else if ((current1->zuo_biao) < (current2->zuo_biao))
		{
			current3->next = current2;
			current3 = current3->next;
			current2 = current2->next;
		}
		else if ((current1->zuo_biao) == (current2->zuo_biao))
		{
			current1->zhen_de_shu_ju += current2->zhen_de_shu_ju;
			current3->next = current1;
			current3 = current3->next;
			current1 = current1->next;
			lianbiao* temp=current2;
			current2 = current2->next;
			delete temp;
		}		
	}

	if (current1 != NULL)
		{
			current3->next = current1;
			current3 = current3->next;
			current1 = current1->next;
		}
	else if (current2 != NULL)
		{
			current3->next = current2;
			current3 = current3->next;
			current2 = current2->next;
		}
	
	next = next->next;

}
void lianbiao::input()	//输入数据
{	
	next=	new lianbiao;

	lianbiao* current = next;
	cin >>current-> zhen_de_shu_ju >> current->zuo_biao;
	
	while (cin.get() != '\n')
	{	
		current->next = new lianbiao;
		current = current->next;				
		cin >> current->zhen_de_shu_ju >> current->zuo_biao;
	}
	

}

void  lianbiao::output()	//输出数据
{
	lianbiao* current=next;
	while (current!=nullptr)
	{		
		if (current->zhen_de_shu_ju)
		{
		cout << current->zhen_de_shu_ju << " " << current->zuo_biao << " ";				
		}
		current = current->next;	
	}
}
void lianbiao::shoudong()	//手动析构
{
	lianbiao *temp1;
	while (next != NULL)
	{		
		temp1 = next;
		next = next->next;
		delete temp1;
	}
}

int main()
{
	lianbiao head1,head2,head3;
    cout <<"输入第一个多项式\n';
	head1.input();
    cout <<"输入第二个多项式\n";
	head2.input();
    cout <<"结果\n";
	head3.add(head1, head2);
	head3.output();

	head3.shoudong();

	return 0;
}

注:本文仅供本人记录学习之用,多有瑕疵,请友好讨论。