#include <iostream>
#include <cstdlib>

using namespace std;

class Term {
    private:
       double coef;
       int    expo;
       Term*  sgte;
    public:
       Term(double c=0.0, int e=0, Term* sgte=NULL);
       double Coef() const { return coef; };
       int    Expo() const { return expo; };
       Term*& Sgte() { return sgte; };
};


Term::Term(double c, int e, Term* s)
{
   coef= c;
   expo= e;
   sgte= s;
}

Term*  Ins(Term* p, Term* t)
{
   if (p==NULL)
     {
      t->Sgte()= NULL;
      return t; 
     }

   if (t==NULL)
     return t;

   if (t->Coef()==0.0)
      {
       delete t;
       return p;
      }

   Term* v= p;
   Term* r= NULL;
   while (v!=NULL && v->Expo() >  t->Expo())
     {
      r= v;
      v= v->Sgte();
     }
    
   if (r==NULL)  // v no avanzo, t va al frente
      {
       if (v==NULL)
          return t;

       if (v->Expo() == t->Expo())
          {
           double s= v->Coef() + t->Coef();
           if (s != 0.0)
               p=new Term(s, t->Expo(), v->Sgte());
           else
               p= v->Sgte();
           delete v;
           delete t;
           return p;
          } 
       else
          {
           t->Sgte()= p;
           return t;
          }
      }
   else
      {
       if (v==NULL)
          {
           r->Sgte()= t;
           return p;
          }

       if (v->Expo() == t->Expo())
          {
           double s= v->Coef() + t->Coef();
           if (s != 0.0)
               r->Sgte()=new Term(s, t->Expo(), v->Sgte());
           else
               r->Sgte()= v->Sgte();
           delete v;
           delete t;
           return p;
          } 
       else
          {
           r->Sgte()= t;
           t->Sgte()= v;
           return p;
          }
      
      }
}

void Print(Term* p)
{
    for (Term* q= p; q!= NULL; q= q->Sgte())
       cout << "(" << q->Coef() 
            << "x^" << q->Expo() 
            << ") ";
}


int main(int nargs, char* args[])
{
   Term* p=NULL;

   p= Ins(p, new Term(5,8));
   cout << "p= ";
   Print(p);
   cout << endl;

   p= Ins(p, new Term(2,4));
   cout << "p= ";
   Print(p);
   cout << endl;

   p= Ins(p, new Term(3,6));
   cout << "p= ";
   Print(p);
   cout << endl;

   p= Ins(p, new Term(-3,6));
   cout << "p= ";
   Print(p);
   cout << endl;

   p= Ins(p, new Term(-2,4));
   cout << "p= ";
   Print(p);
   cout << endl;

   p= Ins(p, new Term(-5,8));
   cout << "p= ";
   Print(p);
   cout << endl;

   return EXIT_SUCCESS;
}







