线性表的应用(一元多项式的表示及相加)
题目:若A = a0x0+ a1x1+a2x2+a3x3+…+anxn
B = b0x0+ b1x1+b2x2+b3x3+…+bnxn
求A+B
- 顺序存储结构的实现
①实现一个数组每两个元素为一个单位,左边指数,右边是系数。从系数为0,一直写到最大的那个系数。
②利用链表的思维
上大,上移
上小,下插入上。上移名
上下相等,系数和不为0,相加后写入上,上移和下移;系数和不为0,后面的数组前移,上移,下移;最后要清空下数组、
2.链式存储结构的实现
//定义结构体,exp为指数,coef为系数,next为下一个结点
typedef struct LNode{
int exp;
int coef;
LNode* next;
}LNode,* LinkList;
//初始化链表
void initLinkList(LinkList &L){
L = new LNode;
L->next =nullptr;
}
//向链表最后一个插入值
void insert(LinkList&L , int exp,int coef){
LNode* p = L;
while (p->next != nullptr) {
p=p->next;
}
LNode *elam = new LNode{exp,coef,nullptr};
elam->next = p->next;
p->next = elam;
p = p->next;
}
//计算两个多项式的和
void addTwoLinkList(LinkList &A,LinkList &B){
LNode* p = A->next;
LNode* q = B->next;
LNode* pre = A;
LNode* qre = B;
while (p!= nullptr && q!= nullptr) {
if (p->exp < q->exp) {
p = p->next;
pre = pre->next;
}else if(p->exp>q->exp){
LNode* cur = q->next;
q->next = p;
pre->next =q;
q = cur;
}else{
if (p->exp + q->exp != 0) {
p->coef += q->coef;
p = p->next;
}else{
pre->next = p->next;
delete p;
p=pre->next;
}
qre->next = q->next;
delete q;
q = qre->next;
}
}
if (q!= nullptr) {
q->next =q;
}
delete B;
}
//测试数据
int main(){
LinkList A;
LinkList B;
initLinkList(A);
insert(A, 2, 3);
insert(A, 3, 1);
insert(A, 5, 6);
insert(A, 7, 5);
LNode* p = A->next;
while (p != nullptr) {
cout<<p->coef<<"X"<<p->exp<<"+";
p= p->next;
}
cout<<endl;
initLinkList(B);
insert(B, 2, 3);
insert(B, 3, 1);
insert(B, 5, 6);
insert(B, 7, 5);
addTwoLinkList(A, B);
LNode* p1 = A->next;
while (p1 != nullptr) {
cout<<p1->coef<<"X"<<p1->exp<<"+";
p1= p1->next;
}
cout<<endl;
}