一元多项式的加减法

tips: 三月份写过这个题解,当时确实解决了当时问题,但是方法是错的,两个月后,又做类似的题目,只是将指数由大到小的排列便错了,那么我就不(敢)再误人子弟,便删去旧的题解,写新的题解。这一次经历了两天来研究指针的问题,可以说,过程比较令人头大,但是对指针的了解也更多了一些。功不唐捐!

在学习链表的过程中,了解到可以使用链表的方式来实现一元多项式的加减(还打算实现乘法和除法,但是技术有限,一时不一会写,哈哈,以后或许会悄悄更新吧)

如何获取到两个一元多项式

我们可以使用到首先明确一共有多少项,输入数据应该如下示例:
如果希望输入的多项式是:x+2x^2+3x^3
那么输入的数据应该是: 3 1 1 2 2 3 3
第一个输入一共多少项,之后我们可以依次输入每项的底数和次方。

储存方式

自然是使用链表咯!

代码里面见分析!

精华应该是在于对于

#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
	int coef;
	int index;
	struct Node* next;
}node;

int main(){	
	int n;
	cin>>n;
	int coef;
	int index;
	node* head1 = (node*)malloc(sizeof(node));
	node* headfirst = head1;
	for(int i=0;i<n;i++){
		node* t = (node*)malloc(sizeof(node));
		cin>>t->coef;
		cin>>t->index;
		head1->next = t;
		head1 = head1->next;			
	}
	head1->next = NULL;

	cin>>n;
	node* head2 = (node*)malloc(sizeof(node));
	node* headsecond = head2;
	for(int i=0;i<n;i++){
		node* t = (node*)malloc(sizeof(node));
		cin>>t->coef;
		cin>>t->index;
		head2->next = t;
		head2 = head2->next;			
	}
	head2->next = NULL;



	//start  
	Node* tail = headfirst;
	Node* p = headfirst->next;
	Node* q = headsecond->next;
	Node* t = headfirst;//as the result
	while(q&&p){
		if(p->index > q->index){
			tail = p;
			p= p->next;
		}
		if(p->index < q->index){
			tail->next = q;
			tail = q;
			q = q->next; 
		}	
		else{
			if(p->coef + q->coef==0){
				tail->next = p->next;
				Node* temp = p;	
				p = p->next;
				free(temp);
				temp = q;
				q= q->next;
				free(temp);
			} 
			else {//coef之和不为0,index相等时 
				p->coef = p->coef + q->coef;
				tail ->next = p;
				p = p->next;
				Node* temp = q;
				q = q->next;		
				free(temp);
			}
		}	
	}
    t = t->next;
	while(t){
		if(t!=headfirst->next&&t->coef>0)cout<<"+";
		cout<<t->coef<<"x";
		if(t->index!=1)cout<<"^"<<t->index;
		t = t->next;
		
	}
	return 0;
	
}