/**
* 编译器:vs2010
* @fencaide 2017年12月3日12:42:30
*/
#include
using namespace std;
typedef struct SNode* Polynomial;
struct SNode{
int coefficient;//系数
int index;//指数
Polynomial next;
};
Polynomial attach(int coefficient=0, int index=0){
Polynomial list = new(struct SNode);
list->coefficient = coefficient;
list->index = index;
list->next = NULL;
return list;
}
Polynomial ReadyPoly(int n){
int number1,number2;
Polynomial head = NULL;
Polynomial list = NULL;
cout<<"Please input the coeddicients and index"< while(n--){
cin>>number1>>number2;
Polynomial elem = attach(number1, number2);
if(NULL == head){
//第一次赋值head
list = elem;
head = list;
}
else{
list->next = elem;
list = list->next;
}
}
return head;
}
/*
Polynomial CopyPoly(Polynomial &from){
Polynomial iterator = from;
Polynomial head = NULL;
Polynomial list = NULL;
while(iterator->next){
Polynomial elem = attach(iterator->coefficient, iterator->index);
if(NULL == head){
//第一次赋值head
list = elem;
head = list;
}
else{
list->next = elem;
list = list->next;
}
}
return head;
}*/
Polynomial add( Polynomial & list1,Polynomial & list2){
Polynomial head = NULL;
Polynomial elem = NULL;
Polynomial list = NULL;
//Polynomial List = CopyPoly(list1);
//这里假设list1 和list2 都是合并同类项且按照次数由高到低排序后的多项式
while(1){
if(NULL == list1 && NULL == list2){
break;
}
else if(NULL == list1){
list->next = list2;
break;
}
else if(NULL == list2){
list->next = list1;
break;
}
else if(list1->index == list2->index){
elem = attach(list1->coefficient + list2->coefficient, list1->index);
//都后移
list1 = list1->next;
list2 = list2->next;
}
else if(list1->index > list2->index){
elem = attach(list1->coefficient, list1->index);
//1后移
list1 = list1->next;
}
else{
elem = attach(list2->coefficient, list2->index);
//2后移
list2 = list2->next;
}
//添加到list中去
if(NULL == head){
//第一次赋值head
list = elem;
head = list;
}
else{
list->next = elem;
list = list->next;
}
}
return head;
}
void printPoly(Polynomial &list){
Polynomial p = list;
while(p){
cout<<"( "<coefficient<<","<index<<" )"< p = p->next;
}
}
void gc(Polynomial &list){
Polynomial p = list;
cout<<"Program is free memory..."< while(p){
Polynomial q = p;
p = p->next;
delete q;
}
}
int main()
{
int count,n=2;
Polynomial list1=NULL,list2=NULL;
cout<<"Please input times of input."< cin>>count;
list1 = ReadyPoly(count);
printPoly(list1);
cout<<"Please input times of input."< cin>>count;
list2 = ReadyPoly(count);
printPoly(list2);
cout<<"Add result is:"< Polynomial list = add(list1, list2);;
printPoly(list);
gc(list1);
gc(list2);
gc(list);
getchar();
getchar();
return 0;
}