ac.c

来自「多项式相加的计算 多项式相加的计算」· C语言 代码 · 共 104 行

C
104
字号

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define  LEN  sizeof(node)

typedef struct polynode
{
 int coef;
 int exp;
 struct polynode *next;
}node;

node * create(void)
{
 node *h,*r,*s;
 int c,e;
 h=(node *)malloc(LEN);
 r=h;
 printf("coef:");
 scanf("%d",&c);
 printf("exp: ");
 scanf("%d",&e);
 while(c!=0)
 {
  s=(node *)malloc(LEN);
  s->coef=c;
  s->exp=e;
     r->next=s;
     r=s;
     printf("coef:");
     scanf("%d",&c);
     printf("exp: ");
     scanf("%d",&e);
 }
 r->next=NULL;
 return(h);
}
 
void polyadd(node *polya, node *polyb)
{
 node *p,*q,*pre,*temp;
 int sum;
 p=polya->next;
 q=polyb->next;
 pre=polya;
 while(p!=NULL&&q!=NULL)
 {
  if(p->exp<q->exp)
  {
   pre->next=p;pre=pre->next;
   p=p->next;
  }
  else if(p->exp==q->exp)
  {
   sum=p->coef+q->coef;
   if(sum!=0)
   {
    p->coef=sum;
    pre->next=p;pre=pre->next;
    p=p->next;temp=q;q=q->next;free(temp);
   }
   else
   {temp=p->next;free(p);p=temp;
    temp=q->next;free(q);q=temp;
   }
     }
 else 
 {pre->next=q;pre=pre->next;
  q=q->next;
 }
    }
if(p!=NULL)
pre->next=p;
else
pre->next=q;                                                         
}

void print(node * p)
{                                                                                                      
    while(p->next!=NULL)
    {   
        p=p->next;
        printf("     %d*x^%d",p->coef,p->exp);   
           
    }
}  
main()
{
 node * polya,* polyb;
 printf("Welcome to use!\n");
 printf("\nPlease input the ploya include coef && exp:\n");
 polya=create();
 print(polya);
 printf("\nPlease input the ployb include coef && exp:\n");
 polyb=create();
 print(polyb);
    printf("\nSum of the poly is:\n");
    polyadd(polya,polyb);
    print(polya);
    printf("\n");
}

⌨️ 快捷键说明

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