文章目录
一、求两个一元多项式的和
题目:输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输入样例
4 3 4 -5 2 6 1 -2 0
3 5 20 -7 4 3 1
输出样例
5 20 -4 4 -5 2 9 1 -2 0
对于此题我们可以多创建一个链表,然后在对两个链表的指数进行判断,放入新的链表里,空间复杂度是O(n)。
也可以将两个链表合并成一个对于系数为0的节点释放掉。
(代码空间复杂度为O(n))
#include <iostream>
using namespace std;
typedef struct node* List;
struct node
{
int num;
int ex;
List next;
};
List makelist()
{
List L = (List)malloc(sizeof(struct node));
L->next = NULL;
return L;
}
void insert(List L, int a, int b)
{
List head = L;
while (head->next != NULL)
head = head->next;
List k = (List)malloc(sizeof(struct node));
k->num = a;
k->ex = b;
k->next = NULL;
head->next = k;
}
int add(List L1, List L2, List L3)
{
int s = 0;
List head1 = L1->next;
List head2 = L2->next;
List head3 = L3;
while (head1 != NULL && head2 != NULL)
{
if (head1->ex == head2->ex)
{
List q = (List)malloc(sizeof(struct node));
q->num = head1->num + head2->num;
if(q->num==0)
{
head1 = head1->next;
head2 = head2->next;
continue;
}
q->ex = head1->ex;
q->next = NULL;
head3->next = q;
head3 = head3->next;
head1 = head1->next;
head2 = head2->next;
s++;
}
else if (head1->ex > head2->ex)
{
List p = (List)malloc(sizeof(struct node));
p->num = head1->num;
p->ex = head1->ex;
p->next = NULL;
head3->next = p;
head3 = head3->next;
head1 = head1->next;
s++;
}
else if (head1->ex < head2->ex)
{
List j = (List)malloc(sizeof(struct node));
j->num = head2->num;
j->ex = head2->ex;
j->next = NULL;
head3->next = j;
head3 = head3->next;
head2 = head2->next;
s++;
}
}
if (head1 != NULL)
{
head3->next = head1;
s++;
}
if (head2 != NULL)
{
head3->next = head2;
s++;
}
return s;
}
int main()
{
List L1 = makelist();
List L2 = makelist();
List L3 = makelist();
int n, i, s, a, b, m;
cin >> n;
for (i = 0;i < n;i++)
{
cin >> a >> b;
insert(L1, a, b);
}
cin >> m;
for (i = 0;i < m;i++)
{
cin >> a >> b;
insert(L2, a, b);
}
s = add(L1, L2, L3);
if (s == 0)
{
cout << 0 << " " << 0 << endl;
return 0;
}
List Phead = L3->next;
while (Phead != NULL)
{
cout << Phead->num << " " << Phead->ex;
if (Phead->next != NULL)
cout << " ";
Phead = Phead->next;
}
}