运行结果和代码如下:
#ifndef LinkList_H
#define LinkList_H
#include<iostream>
using namespace std;
template<typename T>
struct Node
{
T coef;//系数
T ind;//指数
Node<T>*next;
};
template<typename T>
class Linklist
{
public:
Linklist();
~Linklist();
void create();
void printlist();
void add(Linklist r,Linklist t);
private:
Node<T>*first;
};
#endif
```c++
#include"one letter polynomial2.h"
template<typename T>
Linklist<T>::Linklist()
{
first=new Node<T>;
first->next=NULL;
}
template<typename T>
void Linklist<T>::create()
{
first=new Node<T>;
first->next=NULL;
int a,b;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
Node<T>*s=NULL;
s=new Node<T>;
s->coef =a;
s->ind=b;
cin>>s->coef>>s->ind;
s->next=first->next;
first->next=s;
}
}
template<typename T>
Linklist<T>::~Linklist()
{
}
template<typename T>
void Linklist<T>::printlist()
{
Node<T> *p;
p=first->next;
if(p!=NULL)
{
cout<<p->coef<<" "<<p->ind<<endl;
p=p->next;
};
}
template<typename T>
void Linklist<T>::add(Linklist a,Linklist b)
{
Node<T> *p,*q;
Node<T> *s;
Node<T> *r;
Linklist c;//新建链表c
r=c.first;//r指向c的头结点
p=a.first->next;//p指向a的第一个结点
q=b.first->next;//q指向b的第一个结点
while(q&&p)
{
if(p->ind >q->ind )
{
s=new Node<T>;
s->coef =p->coef ;
s->ind =p->ind ;
r->next=s;
r=s;
p=p->next;
}
else if(p->ind ==q->ind )
{
if(p->coef+q->coef==0 )
{
p=p->next ;
q=q->next ;
}
else
{
s=new Node<T>;
s->ind =p->ind ;
s->coef =p->coef +q->coef ;
r->next=s;
r=s;
p=p->next ;
q=q->next ;
}
}
else
{
s=new Node<T>;
s->coef =q->coef ;
s->ind =q->ind ;
r->next=s;
r=s;
q=q->next;
}
}
r->next=NULL;
if(p!=NULL) r->next =p;
if(q!=NULL) r->next =q;
c.printlist();
}
```c++
#include <iostream>
#include"one letter polynomial.cpp"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
Linklist <int>a,b;
a.create();
b.create();
a.add(a,b);
return 0;
}
运行结果如下所示: