#include<bits/stdc++.h>
using namespace std;
typedef struct node *p;
struct node{
int a;
int b;
struct node *next;
};
typedef p l;
l read();
l add(l l1,l l2);
void print(l l1);
l m(l l1,l l2);
l mul(l l1,l l2);
int main()
{
l l1,l2,l3,l4;
l1=read();
l2=read();
l3=add(l1,l2);
l4=m(l1,l2);
print(l4);
print(l3);
return 0;
}
l read()
{
l p=(l)malloc(sizeof(node));
l head;
p->next=NULL;
head=p;
int n;
cin>>n;
while(n--)
{
l t=(l)malloc(sizeof(node));
t->next=NULL;
cin>>t->a>>t->b;
p->next=t;
p=t;
}
return head;
}
l add(l l1,l l2)
{
l t1,t2;
t1=l1->next;
t2=l2->next;
l t=(l)malloc(sizeof(node));
t->next=NULL;
l head;
head=t;
while(t1&&t2)
{
l temp=(l)malloc(sizeof(node));
temp->next=NULL;
if(t1->b<t2->b)
{
temp->a=t2->a;
temp->b=t2->b;
t->next=temp;
t=temp;
t2=t2->next;
}
else if(t1->b>t2->b)
{
temp->a=t1->a;
temp->b=t1->b;
t->next=temp;
t=temp;
t1=t1->next;
}
else if(t1->b==t2->b)
{
if(t1->a+t2->a==0)
{
t1=t1->next;
t2=t2->next;
}
else
{
temp->a=t1->a+t2->a;
temp->b=t1->b;
t1=t1->next;
t2=t2->next;
t->next=temp;
t=temp;
}
}
}
if(!t1)
{
t->next=t2;
}
else if(!t2)
t->next=t1;
return head;
}
void print(l l1)
{
l p;
p=l1->next;
if(!p)
{
cout<<"0"<<" "<<"0"<<endl;
}
else
while(p)
{
if(p->next!=NULL)
{
cout<<p->a<<" "<<p->b<<" ";
p=p->next;
}
else
{
cout<<p->a<<" "<<p->b<<endl;
p=p->next;
}
}
}
l m(l l1,l l2)
{
l head,p;
p=(l)malloc(sizeof(node));
p->next=NULL;
head=p;
l t1,t2;
t1=l1->next;
t2=l2->next;
l temp;
if(t1&&t2)
{
temp=mul(l1,t2);
t2=t2->next;
while(t2)
{
l te=mul(l1,t2);
temp=add(temp,te);
t2=t2->next;
}
p->next=temp->next;
}
return head;
}
l mul(l l1,l l2)
{
l head,p;
p=(l)malloc(sizeof(node));
p->next=NULL;
head=p;
l t1;
t1=l1->next;
while(t1)
{
l L=(l)malloc(sizeof(node));
L->next=NULL;
L->a=t1->a*l2->a;
L->b=t1->b+l2->b;
t1=t1->next;
p->next=L;
p=L;
}
return head;
}
对于这题其实很中规中矩,需要小心的使用链表,
总结:
1.一定要有个头结点作为返回,因为它是指向第一个节点;
2.既然头结点不能移动,那么就需要一个新的节点作为移动,同时对它更新;
3.如果添加节点,那么要动态分配一个空间节点;