内容
实现一元多项式的加法(需要编写可运行程序)要求:
1、通过键盘随机输入两个多项式P(x)和Q(x)的内容。
2、输出结果要有P(x)、Q(x)以及他们的和。
3、输入输出多项式的格式可自行定义。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct NODE{
int idx;
int exp;
struct NODE* next;
};
void QuickSort(struct NODE a[], int left, int right)
{
//快排,从大到小
if(left >= right) return ;
int i = left, j = right, key = a[left].exp;
struct NODE tp=a[left];
while(i < j) {
while(i < j && key >= a[j].exp) j--;
a[i] = a[j];
while(i < j && key <= a[i].exp) i++;
a[j] = a[i];
}
a[i] = tp;
QuickSort(a, left, i - 1);
QuickSort(a, i + 1, right);
}
void Attach(int idx,int exp, struct NODE** pRear){
struct NODE* P;
P = (struct NODE*)malloc(sizeof(struct NODE*));
P->exp=exp;
P->idx=idx;
P->next=NULL;
(*pRear)->next=P;
*pRear = P;
}
struct NODE* build(){
struct NODE* P;
struct NODE* Rear;
struct NODE* t;
int n,a,b;
scanf("%d",&n);
P=(struct NODE*)malloc(sizeof(struct NODE));
P->next=NULL;
Rear = P;
while(n--){
scanf("%d%d",&a,&b);
Attach(a,b,&Rear);
}
//删除头结点
t=P;
P=P->next;
free(t);
return P;
}
void mysotr(struct NODE* head){
//先把链表的内容存放到数组中(时间为O(n)),然后对那个数组进行从大到小排序nlog(n)
int i=0,len=0;
struct NODE *p= (struct NODE *) head;
while(p!=NULL){
len++;
p=p->next;
}
struct NODE a[len+2];
p= (struct NODE *) head;
for(i=0;p!=NULL;p=p->next,i++){
a[i].idx=p->idx;
a[i].exp=p->exp;
}
QuickSort(a,0,len-1);
p= (struct NODE *) head;
for(i=0;p!=NULL;p=p->next,i++){
p->idx=a[i].idx;
p->exp=a[i].exp;
}
}
void myprint(struct NODE* head){
if (!head) {
printf("0 0\n");
return;
}
struct NODE *p=head;
while(p!=NULL){
if(p!=head) printf(" ");
printf("%d %d",p->idx,p->exp);
p = p->next;
}
printf("\n");
}
struct NODE* Add(struct NODE* p1,struct NODE* p2){
struct NODE* PS;
struct NODE* rear;
struct NODE* temp;
int sum=0;
PS = (struct NODE*) malloc(sizeof(struct NODE));
PS->next=NULL;
rear = PS;
while(p1!=NULL&&p2!=NULL){
if(p1->exp==p2->exp){
sum = p1->idx+p2->idx;
if(sum) Attach(sum,p1->exp,&rear);
p1 = p1->next;
p2 = p2->next;
}else if(p1->exp>p2->exp){
Attach(p1->idx,p1->exp,&rear);
p1 = p1->next;
}else{
Attach(p2->idx,p2->exp,&rear);
p2 = p2->next;
}
}
while(p1!=NULL){
Attach(p1->idx,p1->exp,&rear);
p1=p1->next;
}
while(p2!=NULL){
Attach(p2->idx,p2->exp,&rear);
p2=p2->next;
}
temp = PS;
PS = PS->next;
free(temp);
return PS;
}
int main() {
struct NODE* P1;
struct NODE* P2;
P1=build(),P2=build();
mysotr(P1),mysotr(P2);
struct NODE* P3;
struct NODE* P4;
P3= Add(P1,P2);
printf("多项式相加的结果是:");
myprint(P3);
return 0;
}
//4 3 4 -5 2 6 1 -2 0
//3 5 20 -7 4 3 1
//4 -9 -1 2 2 3 3 2 1
//3 8 1 -5 4 5 18