问题描述:
把任意给定的两个一元多项式P(x) ,Q(x) 输入计算机,计算它们的和并输出计算结果。一元多项式可以用单链表表示,结点结构图示如下:
一元多项式算法伪代码如下:
1. 工作指针p、q初始化;
2. while(p存在且q存在)执行下列三种情形之一
2.1 如果p->exp<q->exp,则指针p后移;
2.2 如果p->exp>q->exp,则
2.2.1 将结点q插入到结点p之前;
2.2.2 指针q指向原指结点的下一个结点;
2.3 如果p->exp=q->exp,则
2.3.1 p->coef =p->coef+q->coef;
2.3.2 如果p->coef ==0,则执行下列操作,否则,指针p后移;
2.3.2.1 删除结点p;
2.3.2.2 使指针p指向它原指结点的下一个结点;
2.3.3 删除结点q;
2.3.4 使指针q指向它原指结点的下一个结点;
3. 如果q不为空,将结点q链接在第一个单链表的后面;
实现代码
#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct node {
int coef; //系数
int exp; //指数
node* next;
} list;
node* newNode(int c, int e) {
node* temp = (node*)malloc(sizeof(struct node));
temp->coef = c;
temp->exp = e;
temp->next = NULL;
return temp;
}
list* createPoly(int n) {
list* L = NULL;
if (n == 0) {
return L;
}
else {
//创建一个头节点
L = (list*)malloc(sizeof(struct node));
}
int ac = 0;//暂存数据
int ae = 0;
node* lastp = L;//此时L是空的,可以用lastp来做为结点创建sum的链表
node* temp = NULL;//工作指针,用在计算过程中
for (int i = 0; i < n; i++) {
cin >> ac >> ae;
temp = newNode(ac, ae);
//尾插法建立链表
lastp->next = temp;
lastp = temp;
}
return L;
}
list* addPoly(list* A, list* B) {
if (!A->next) return B;
if (!B->next) return A;
node* pa = A->next;//工作指针指向A的头结点
node* pb = B->next;//工作指针指向B的头结点
list* sum = (list*)malloc(sizeof(struct node));
sum->next = NULL;
node* lastp = sum;
node* temp = NULL;
while (pa && pb) {//exp是指数,coef是系数
if (pa->exp == pb->exp) {//pa等于pb
if ((pa->coef + pb->coef) != 0) {
temp = newNode(pa->coef + pb->coef, pa->exp);
//尾插法插入节点
lastp->next = temp;
lastp = temp;
}
pa = pa->next;
pb = pb->next;
}
else if (pa->exp > pb->exp) {//pa大于pb
temp = newNode(pa->coef, pa->exp);
lastp->next = temp;
lastp = temp;
pa = pa->next;
}
else {//pa等于pb
temp = newNode(pb->coef, pb->exp);
lastp->next = temp;
lastp = temp;
pb = pb->next;
}
}
if (pa == NULL && pb != NULL)
lastp->next = pb;
if (pb == NULL && pa != NULL)
lastp->next = pa;
return sum;
}
void printPoly(list* L) {
if (!L->next) {
cout << "0 0";
}
else {
node* p = L->next;
int i = 0;//工作变量
while (p) {//需要注意输出格式控制
if (i == 0) {
cout << p->coef << " " << p->exp;
i++;
}
else {
cout << " " << p->coef << " " << p->exp;
}
p = p->next;
}
}
}
int main(void) {
int n, m;
cin >> n;
list* La = createPoly(n);
cin >> m;
list* Lb = createPoly(m);
list* result = addPoly(La, Lb);
printPoly(result);
return 0;
}
实验结果
如有同校学弟学妹们看到这篇博客,请务必认真自己思考,切忌不要随意CV。