数据结构 一元多项式相加

/***************************/
/*一元多项式相加*/

#include<stdio.h>
#include<stdlib.h>
/
struct node
{
 int coef; //系数
 int expn;   //指数
 struct node *next;
};
typedef struct node polynomial;

/**************建立带有表头的链表**************/
// poly用于保存系数和指数

polynomial *CreatePoly(int poly[], int len)
{
 polynomial *ptr;
 polynomial *newpoly;
 polynomial *head;
 int i;
 head = (polynomial *)malloc(sizeof(polynomial));  //表头
 head->coef = -1;
 head->expn = 0;
 head->next = NULL;
 ptr = head;
 for(i=0; i<len; i+=2)
 {
  newpoly = (polynomial *)malloc(sizeof(polynomial));
  newpoly->coef = poly[i];
  newpoly->expn = poly[i+1];
  newpoly->next = NULL;
  ptr->next = newpoly;
  ptr = newpoly;
 }
 return head;
}

/*********销毁链表**************/
void DestroyPolyn(polynomial *head)
{
 polynomial *ptr;
 ptr = head;
 while(head != NULL)
 { 
  ptr = ptr->next;
  free(head);
  head = ptr;
 }
}
/************输入链表****************/
void PrintPolyn(polynomial *head)
{
 polynomial *ptr;
 ptr = head->next;
 while(ptr != NULL)
 {
  printf("(%d,%d)",ptr->coef, ptr->expn);
  ptr = ptr->next;
 }
 printf("/n");
}

/***********链表相加/*****************/
//参数为两个要相加多项式的链表
//两个链表为从系数大到小排列
polynomial *AddPoly(polynomial *head1, polynomial *head2)
{
 polynomial *ptr1, *ptr2, *ptr;
 polynomial *newpoly;
 polynomial *head;
 head = (polynomial *)malloc(sizeof(polynomial));
 head->coef = -1;
 head->expn = 0;
 head->next = NULL;
 ptr = head;
 ptr1 = head1->next;
 ptr2 = head2->next;

 while(ptr1 != NULL && ptr2 != NULL)  //都不为空时
 {
  newpoly = (polynomial *)malloc(sizeof(polynomial));
  newpoly->next = NULL;
  if(ptr1->expn > ptr2->expn)   //指数大的放到前面
  {
   newpoly->coef = ptr1->coef;
   newpoly->expn = ptr1->expn; 
   ptr1 = ptr1->next;
  }
  else if(ptr1->expn < ptr2->expn)
  {
   newpoly->coef = ptr2->coef;
   newpoly->expn = ptr2->expn;
   ptr2 = ptr2->next;
  }
  else     //两指数相等,则系数=两系数相加
  {
   newpoly->coef = ptr1->coef + ptr2->coef;
   newpoly->expn = ptr1->expn;
   ptr1 = ptr1->next;
   ptr2 = ptr2->next;
  }
  ptr->next = newpoly;
  ptr = newpoly;
 }
 if(NULL == ptr1)    //ptr2 != null, ptr1 == null时
 {
  while(ptr2 != NULL)    //直接复制ptr2到新链表中
  {
   newpoly = (polynomial *)malloc(sizeof(polynomial));
   newpoly->next = NULL;
   newpoly->coef = ptr2->coef;
   newpoly->expn = ptr2->expn;
   ptr->next = newpoly;
   ptr = newpoly;
   ptr2 = ptr2->next;
  }
 }
 else if(NULL == ptr2)
 {
  while(ptr1 != NULL)
  {
   newpoly = (polynomial *)malloc(sizeof(polynomial));
   newpoly->next = NULL;
   newpoly->coef = ptr1->coef;
   newpoly->expn = ptr1->expn;
   ptr->next = newpoly;
   ptr = newpoly;
   ptr1 = ptr1->next;
  }
 }
 return head;
}

展开阅读全文

没有更多推荐了,返回首页