一元多项式求和
比较拉跨基本实现功能,没多少注释 链表头指针不存数据合并同类项要手动 相加是比较拉跨的算法第二个链表与第一个链表中的一个循环比较,最后排序还拉跨算法也许有bug仅作参考
#include <stdio.h>
#include <stdlib.h>
struct List{
int coe;//系数
int exp;//项
struct List *next;
};
void ListSort(struct List *head1)
{
struct List *p,*q;
int temp1,temp2;
p = head1;
p = p->next;
while(p){
q = p->next;
while(q){
if(p->exp > q->exp){
temp1 = p->exp;
p->exp = q->exp;
q->exp = temp1;
temp2 = p->coe;
p->coe = q->coe;
q->coe = temp1;
}
q = q->next;
}
p = p->next;
}
}
void ListDelete(struct List *p,struct List *q,int i)
{
struct List *s;
if((p->exp == i)&&(((q->next)->exp)==i)){
s = q->next ;
q->next = s->next;
free(s);
}
}
void ListJoin(struct List *head1,struct List *head2)
{
struct List *p,*q,*s;
p = head1;
q = head2;
while(p->next){
p = p->next;
}
if(q->next){
s = q->next;
p->next = s;
free(s);
}
}
int Listadd(struct List *head,int i,int data1,int data2)
{
struct List *p,*s;
int j = 0;
p = head;
while(p && j<i-1){
p = p->next;
j++;
}
if(!p||j>i-1)
return 0;
s = (struct List*)malloc(sizeof(List));
s->coe = data1;
s->exp = data2;
s->next = p->next;
p->next = s;
return 1;
}
struct List* ListCreat (void)
{
int data1,data2,i,num,status=0;
struct List *head,*s;
s = (struct List*)malloc(sizeof(List));
s -> next = NULL;
head = s;
printf("输入一元多项式多少项;");
scanf("%d",&num);
for(i=0;i<num;i++){
printf("\n输入系数项数:");
scanf("%d%d",&data1,&data2);
status += Listadd(s,i+1,data1,data2);
}
if(status == num){
printf("CreatSuccess\n");
}else{
printf("CreatFail\n");
}
return head;
}
void ListDisplay(struct List *head)
{
struct List *p;
p = head;
p = p->next;
while(p){
printf("%dX^%d+",p->coe,p->exp);
p = p->next;
}
printf("\b \n");
}
struct List* ListAnd(struct List* head1,struct List* head2) //相加
{
struct List *p,*q,*s,*b;
int dataq1=0,dataq2=0,datap1=0,datap2=0;
p = head1;
q = head2;
while(p->next){
p = p->next;
datap2 = p->exp;
while(q->next){
b = q;
q = q->next;
dataq2 = q->exp;
if(dataq2 == datap2){
p->coe += q->coe ;
ListDelete(p,b,dataq2);//删除已经求和的
q = head2;
break;
}
}
}
ListJoin(head1,head2);//有多余的项相加
ListSort(head1);//排序
return head1;
}
int main (void)
{
struct List* head1;
struct List* head2;
struct List* head3;
head1 = ListCreat ();
head2 = ListCreat ();
ListDisplay(head1);
ListDisplay(head2);
head3 = ListAnd(head1,head2);
ListDisplay(head3);
return 0;
}
后面运行效果