处理多项式

/* 处理多项式 */
#include "stdio.h"
struct plist
{
 int coef;
 int exp;
 struct plist *next;
};
typedef struct plist pnode;
typedef pnode *plink;
/*多项式含头结点的循环链表的输出*/
void printpoly(plink poly)
{
 plink ptr;
 ptr=poly->next;
 while(poly!=ptr)
 {
  /*输出结点数量*/
  printf("%d^%d",ptr->coef,ptr->exp);
  ptr=ptr->next;
     if(poly!=ptr)
  printf("+");
 }
 printf("/n");
}
/*使用数组创建多项式*/
plink createpoly(int *array,int len)
{
 plink head;
 plink before;
 plink new_node;
 int i;
 /*创建头结点*/
 head=(plink)malloc(sizeof(pnode));
 if(!head) return NULL;
 head->exp=-1;
 before=head;
 for(i=len-1;i>=0;i--)
    if(array[i]!=0)
 {
  /*分配结点内存*/
  new_node=(plink)malloc(sizeof(pnode));
  if(!new_node) return NULL;
  new_node->coef=array[i];
  new_node->exp=i;
  new_node->next=NULL;
  before->next=new_node;
  before=new_node;
 }
 new_node->next=head;
 return head;
}
/*多项式相加*/
plink polyadd(plink poly1,plink poly2)
{
 plink head1,head2,result,before,new_node;
 head1=poly1->next;
 head2=poly2->next;
 /*创建头结点而分配结点内存*/
 result=(plink)malloc(sizeof(pnode));
 if(!result) return NULL;
 result->exp=-1;
 before=result;
 while(poly1!=head1||poly2!=head2)
 {
  /*分配内存结点*/
  new_node=(plink)malloc(sizeof(pnode));
  if(!new_node) return NULL;
  if(head1->exp<head2->exp)/*多项式2的指数大*/
  {
   new_node->coef=head2->coef;/*设置系数*/
   new_node->exp=head2->exp;/*设置指数*/
   head2=head2->next;/*指向下一个结点*/
  }
  else
      if(head1->exp>head2->exp)/*多项式1的指数大*/
       {
          new_node->coef=head1->coef;/*设置系数*/
          new_node->exp=head1->exp;/*设置指数*/
          head1=head1->next;/*指向下一个结点*/
       }
       else
       {
        /*系数相加*/
        new_node->coef=head1->coef+head2->coef;
        new_node->exp=head1->exp;/*设置指数*/
        head1=head1->next;/*指向下一个结点*/
        head2=head2->next;/*指向下一个结点*/
       }
  before->next=new_node;/*将前结点指向新结点*/
  before=new_node;/*新结点成为前结点*/
 }
 new_node->next=result;/*创建环状链表*/
 return result;
}
/*主程序*/
void main()
{
    plink poly1,poly2,result;
    int list1[6]={4,0,3,0,7,0};
    int list2[6]={9,7,1,0,5,6};
    poly1=createpoly(list1,6);
    printf("多项式1内容:");
    printpoly(poly1);
    poly2=createpoly(list2,6);
    printf("多项式2内容:");
    printpoly(poly2);
   
    result=polyadd(poly1,poly2);
    printf("多项式相加结果");
    printpoly(result);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值