回 帖 发 新 帖 刷新版面

主题:求解数据结构多项式相加问题!

本人遇到了多项式相加问题,但是不知道怎么解,希望有位大虾能帮忙求解,感激不尽!!我希望包含注释的哦!!

回复列表 (共1个回复)

沙发

#include <stdio.h>
#include <malloc.h>
#include <process.h>
#define NULL 0
#define OK 1
#define ERROR 0
typedef struct duo_fun
{float xi;
 int zhi;
 struct duo_fun *next;
};
#define LEN sizeof(struct duo_fun)
//----------------多项式的基本函数-------------------------
 duo_fun *duo_input()
{//多项式输入
 int n,i;
 duo_fun * head,*p1,*p;
 //创建头结点
 head=(struct duo_fun *)malloc(LEN);
 if(!head) return ERROR;
  head->zhi=-1; head->next=NULL;
  p=head;
  printf("请输入多项式的项数:");
  scanf("%d",&n);
  i=1;
  while(i<=n)
  {p1=(struct duo_fun *)malloc(LEN);
   if(!p1) return ERROR;
   printf("请输入多项式第%d项的系数和指数:",i);
    scanf("%f%d",&p1->xi,&p1->zhi);
    p->next=p1; p=p1; 
    i++;
  }
  p->next=NULL;
  return head;
}
struct duo_fun *duo_add(struct duo_fun *head1,struct duo_fun *head2)
{//多项式相加
struct duo_fun *head3,*p1,*p2,*p3;
 p3=head3=head1; p1=head1->next; p2=head2->next;
 while(p1&&p2)
 {if(p1->zhi==p2->zhi)
 {p1->xi=p1->xi+p2->xi;
  p3->next=p1; p3=p1;p1=p1->next; p2=p2->next;
 }
  else if(p1->zhi>p2->zhi)
  {p3->next=p2;p3=p2;
   p2=p2->next;
  }
      else
      {p3->next=p1; p3=p1;
       p1=p1->next;
      }
 }
 if(p1!=NULL) p3->next=p1;
 if(p2!=NULL) p3->next=p2;
 free(head2);
 return head3;
}
void duo_print(struct duo_fun *head)
{//输出多项式的值
struct duo_fun *p; int n=0;
    p=head->next;
    while(p)
    {n++;
     if(n==1) printf("%.0fx^%d",p->xi,p->zhi);
     else printf("+%.0fx^%d",p->xi,p->zhi);
    p=p->next;
    }
    printf("\n");

}
void duo_add()
{struct duo_fun *head1,*head2,*result;
printf("-----多项式相加------\n");
printf("The format: sishu,zhishu\n");
printf("eg:Input 2,1 2,2 2,5 the result: 2x^1+2x^2+2x^5\n");
printf("请输入第一个多项式 A:\n");
head1=duo_input();
printf("A=");
duo_print(head1);
printf("请输入第二个多项式 B:\n");
head2=duo_input();
printf("B=");
duo_print(head2);
result=duo_add(head1,head2);
printf("\nC=A+B=");
duo_print(result);
printf("\n");
}
void welcome()
{char c;
printf("-------------welcome to here---------------\n");
printf("thank you to use soft!\n");
printf("Do you want to continue?(y/n):");
scanf("%c",&c);
getchar();
if(c=='y' ||c=='Y') printf("OK\n");
else exit(0);
//return OK;
}
main()
{char c;
welcome();
duo_add();
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册