本贴用单链表实现多项式的加法运算,为简单起见,限定系数和指数均为整数,此例是结合数据结构中的链表的操作而编写的,由于鄙人能力有限,所以一定存在着不少bug,暂且不考虑输入错误的时候,程序的容错性,就确定在输入正确的前提下,输出的结果是否完全正确也有待考察!希望各位网友不吝赐教![em2]

完整c++代码(可以运行)


#define NULL 0
#include "iostream.h"
struct polynomial{
    int coef;
    int expn;
    struct polynomial *next;
};
struct polynomial *create_polynomial(struct polynomial *head)
{

     struct polynomial *p;
     struct polynomial *q;
     struct polynomial *prior;
     head=new polynomial;
     cin>>head->coef>>head->expn;
     head->next=NULL;
     p=head;
     q=head;
     if(p->coef==0 && p->expn==0)return NULL;
     while(!(p->coef==0 && p->expn==0))
         {
              p=new polynomial;
              cin>>p->coef>>p->expn;
              p->next=NULL;
              q->next=p;
              prior=q;
              q=p;
         }
     prior->next=NULL;
     return(head);
}
print(struct polynomial *head)
{
    if (head==NULL)return NULL;
    struct polynomial *p;
    p=head;
    if(p!=NULL)
    {
        cout<<p->coef<<"x^"<<p->expn;
        p=p->next;
    }
    while(p!=NULL)
    {   if(p->coef>0)
        {
            cout<<"+"<<p->coef<<"x^"<<p->expn;
        }
        if(p->coef<0)
        {
            cout<<p->coef<<"x^"<<p->expn;
        }
            p=p->next;
    }
}(未完)