乘法我偷懒了,直接用了map,如果需要排序,在map里嵌套一个vector就可以,但是我也很懒的没有写
#include<bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b; i ++ )
#define per(i, a, b) for(int i = a; i >= b; i -- )
using namespace std;
typedef struct Node{
int xs, zs;
Node * next;
} * LNode;
int n, n1, n2;
map<int, int> mp;
void printLNode(LNode & L)
{
cout << "链表输出如下:\n";
LNode head;
head = L;
while(head -> next != NULL){
cout << head -> next -> xs << "x^";
cout << head -> next -> zs << "+";
head = head -> next;
}
cout << endl;
}
void InitNode(LNode & L)
{
L = (LNode) malloc (sizeof(Node));
if(!L){
cout << "链表申请失败\n";
} else {
L -> next = NULL;
// cout << "链表申请成功\n";
}
return ;
}
int ScannerNode(LNode & L)
{
LNode head, p;
head = L;
cout << "请输入你要输入的多项式项数:";
cin >> n;
cout << "请输入你要输入的系数和指数:\n";
rep(i, 1, n){
p = (LNode) malloc (sizeof(Node));
int n1, n2;
cin >> n1 >> n2;
p -> xs = n1;
p -> zs = n2;
head -> next = p;
head = p;
}
head -> next = NULL;
// printLNode(L);
return n;
}
void AndPoly(LNode & L1, LNode & L2)
{
LNode L3, h1 = L1, h2 = L2, p;
InitNode(L3);
LNode h3 = L3;
while(h1 -> next != NULL && h2 -> next != NULL){
// cout << "fghiu";
p = (LNode) malloc (sizeof(Node));
if(h1 -> next -> zs > h2 -> next -> zs) {
p -> zs = h2 -> next -> zs;
p -> xs = h2 -> next -> xs;
h3 -> next = p;
h3 = p;
h2 = h2 -> next;
} else if(h1 -> next -> zs < h2 -> next -> zs) {
p -> zs = h1 -> next -> zs;
p -> xs = h1 -> next -> xs;
h3 -> next = p;
h3 = p;
h1 = h1 -> next;
} else {
p -> zs = h2 -> next -> zs;
p -> xs = h2 -> next -> xs + h1 -> next -> xs;
h3 -> next = p;
h3 = p;
h2 = h2 -> next;
h1 = h1 -> next;
}
// cout << "p = " << p -> xs << endl;
}
if(h1 -> next == NULL){
while(h2 -> next != NULL){
p = (LNode) malloc (sizeof(Node));
p -> xs = h2 -> next -> xs;
p -> zs = h2 -> next -> zs;
h2 = h2 -> next;
h3 -> next = p;
h3 = p;
}
} else {
while(h2 -> next != NULL){
p = (LNode) malloc (sizeof(Node));
p -> xs = h1 -> next -> xs;
p -> zs = h1 -> next -> zs;
h2 = h1 -> next;
h3 -> next = p;
h3 = p;
}
}
h3 -> next = NULL;
printLNode(L3);
}
void MultiplyPoly(LNode & L1, LNode & L2)
{
LNode L3, h1 = L1, h2 = L2, p;
InitNode(L3);
LNode h3 = L3;
// cout << "vha";
rep(i, 1, n1){
// cout << "fas";
h2 = L2;
rep(j, 1, n2){
mp[h1 -> next -> zs + h2 -> next -> zs] += h1 -> next -> xs * h2 -> next -> xs;
h2 = h2 -> next;
}
h1 = h1 -> next;
}
map<int, int> :: iterator it;
int len = mp.size();
int cnt = 1;
for(it = mp.begin(); it != mp.end(); it ++ ){
if(cnt == len){
cout << it -> second << "x^" << it -> first;
} else {
cout << it -> second << "x^" << it -> first << "+";
}
cnt ++;
}
}
int main()
{
cout << "多项式的加乘操作:\n";
LNode L1, L2;
InitNode(L1);
n1 = ScannerNode(L1);
char op;
cin >> op;
if(op == '+'){
InitNode(L2);
n2 = ScannerNode(L2);
AndPoly(L1, L2);
} else {
InitNode(L2);
n2 = ScannerNode(L2);
MultiplyPoly(L1, L2);
}
return 0;
}