我大概只想记录下这一长串的代码……^ ^
#include<iostream>
using namespace std;
const int N = 1010;
struct Node
{
int a;
int m;
struct Node * next;
};
struct Node * Create(int n)
{
struct Node * head, *p, *q;
if(n == 0)
{
// int x; cin >> x;
head = (struct Node *)malloc(sizeof(struct Node));
head->a = 0, head->m = 0;
head->next = NULL;
return head;
}
for(int i = 0; i < n; i++)
{
int a, m;
cin >> a >> m;
p = (struct Node *) malloc(sizeof(struct Node));
p->a = a; p->m = m;
if(i == 0){
head = p;
q = p;
}
else{
q->next = p;
q = p;
}
}
q->next = NULL;
return head;
}
void print(struct Node * head)
{
if(head == NULL)
{
cout << "0 0";
return;
}
struct Node *p;
p = head;
do{
if(p->a != 0)
cout << p->a << " " << p->m;
if(p->next!= NULL && p->next->a != 0 ) printf(" ");
p = p->next;
}while(p != NULL);
}
struct Node * add(struct Node *head1, struct Node *head2)
{
struct Node *head = NULL, *pp, *qq, *p, *q = NULL;
int flag = 1;//判断是否有队头
pp = head1;
qq = head2;
while(pp && qq)
{
if(pp->m < qq->m)
{
if(flag)
{
p = (struct Node *) malloc(sizeof(struct Node));
head = p;
q = p;
p->a = qq->a;
p->m = qq->m;
qq = qq->next;
flag = 0;
}
else
{
p = (struct Node *) malloc(sizeof(struct Node));
p->a = qq->a;
p->m = qq->m;
q->next = p;
q = p;
qq = qq->next;
}
}
else if(pp->m == qq->m)
{
int tmp = pp->a + qq->a;
if(tmp){
p = (struct Node *) malloc(sizeof(struct Node));
p->m = pp->m; p->a = tmp;
if(flag)
{
head = p;
q = p;
flag = 0;
}
else
{
q->next = p;
q = p;
}
qq = qq->next; pp = pp->next;
}
else{
// if(pp->m == 0)
// {
// head = p;
// q = p;
// p->m = pp->m; p->a = tmp;
// }
qq = qq->next; pp = pp->next;
}
}
else
{
if(flag)
{
p = (struct Node *) malloc(sizeof(struct Node));
head = p;
q = p;
p->a = pp->a;
p->m = pp->m;
pp = pp->next;
flag = 0;
}
else
{
p = (struct Node *) malloc(sizeof(struct Node));
p->a = pp->a;
p->m = pp->m;
q->next = p;
q = p;
pp = pp->next;
}
}
}
if(q!=NULL)q->next = NULL;
if(pp)
{
q->next = pp;
}
if(qq)
{
q->next = qq;
}
return head;
}
struct Node *mult(struct Node *head1, struct Node *head2)
{
struct Node *pp, *qq,*head, *p, *q, *head3;
pp = head1; qq = head2;
if((head1->m == 0 && head1->a ==0) || (head2->m==0 && head2->a == 0)) return NULL;
head = (struct Node *)malloc(sizeof(struct Node));
int flag2 = 1;
while(qq)
{
int flag = 1;//
while(pp)
{
p = (struct Node *)malloc(sizeof(struct Node));
p->a = qq->a * pp->a;
p->m = qq->m + pp->m;
if(flag){
head3 = p;
q = p;
flag = 0;
}
else{
q->next = p;
q = p;
}
pp = pp->next;
}
q->next = NULL;
qq = qq->next;
pp = head1;
if(flag2){
head = head3; flag2 = 0;
}
else head = add(head,head3);
}
return head;
}
int main()
{
int m, n;
cin >> m;
struct Node *head1, *head2,*head;
head1 = Create(m);
cin >> n;
head2 = Create(n);
head = mult(head1,head2);
print(head);
cout << endl;
head = add(head1,head2);
print(head);
free(head1);
free(head2);
free(head);
return 0;
}
一直以为0多项输入是0 0然后de了无数个小时:)看了别的博主说输入是0的时候拳头攥起来了