⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 struct001.cpp

📁 用单链表创建两个多项式
💻 CPP
字号:
//   单链表  多项式相加
#include"stdio.h"
#include"stdlib.h"
typedef struct Polynode
  {
    int coef,exp;
    Polynode *next;
  }Polynode,*Polylist;
Polylist polyadd(Polylist poa,Polylist pob);


Polylist polyadd(Polylist poa,Polylist pob)
  {
    Polynode *p,*q,*tail,*temp;
    int sum=0;
      p=poa->next;
      q=pob->next;
      tail=poa;
      while(p!=NULL&&q!=NULL)
        {
          if (p->exp<q->exp)
            {
              tail->next=p;tail=p;p=p->next;
            }
          else 
            if (p->exp==q->exp)
              {
                sum=p->coef+q->coef;
                if (sum!=0)
                  {
                    p->coef=sum;
                    tail->next=p;tail=p;
                    p=p->next;
                    temp=q;q=q->next;free(temp);
                  }
                 else
                   {
                     temp=p;p=p->next;free(temp);
                     temp=q;q=q->next;free(temp);
                    }
              }
            else 
              {
                tail->next=q;tail=q;
                q=q->next;
              }
           }
         if (p!=NULL)
         tail->next=p;
         else tail->next=q;
        return poa;
      }
Polylist polycreate()
  {
    Polynode *head,*rear,*s;
    int c,e;
      head=(Polynode *)malloc(sizeof(Polynode));
      rear=head;
      scanf("%d,%d",&c,&e);
       while(c!=0)
        {
          s=(Polynode *)malloc(sizeof(Polynode));
          s->coef=c;
          s->exp=e;
          rear->next=s;
          rear=s;
          
          scanf("%d,%d",&c,&e);
        }
      rear->next=NULL;
      return(head);
  }


void main()
  {
   
    Polylist polya,polyb,dd;
   
      polya=(Polynode *)malloc(sizeof(Polynode));
      polyb=(Polynode *)malloc(sizeof(Polynode));
      dd=(Polynode *)malloc(sizeof(Polynode));
   
      printf("input number a:");
      polya=polycreate();
      printf("input number b:");
      polyb=polycreate();

    
      dd=polyadd(polya,polyb);
      dd=dd->next;
      printf("%dX%d",dd->coef,dd->exp);
      while(dd->next!=NULL)
        {
          if (dd->next->coef>0) printf("+%dx%d",dd->next->coef,dd->next->exp);
           else printf("%dX%d",dd->next->coef,dd->next->exp);
           dd=dd->next;
        }
     }



 
    
  
    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -