Topic links
Experimental one linked list and its polynomial addition
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 2579 |
|
Accepted: 978 |
Description
By ordering the entries of the input polynomial, the single-linked list is used to store the unary polynomial, and 2 single-linked lists are stored to store the unary polynomial, and then the sum of the 2 unary polynomial is added, and the added polynomial is output.
Input
There are several sets of input data, for each set of test data, the first row an integer n, which represents the number of items in the first polynomial la; next n rows, each row represents an item of a polynomial, contains two elements, represents coefficients and exponents, and the next integer m, which represents the number of items in the second polynomial lb; Each row represents an item of a polynomial, containing two elements, representing coefficients and exponents, and two polynomial inputs that are exponential from small to large. (n,m<=1000)
Output
The polynomial after the addition of LA and LB. According to the index from small to large output, one per line, with a space to separate the coefficients and exponents.
Sample Input 31 22 33 434 32 54 6
Sample Output 1 26 33 42 54 6
Note: The factor may be 0.
#include <iostream> #include <cstdio> using namespace std;
typedef struct linklist{int data,val;
Linklist *next;
}linklist;
Linklist *initlist () {linklist *head= (linklist *) malloc (sizeof (linklist));
head->next=null;
return head;
} linklist *listinsert (linklist *head,int data,int val) {linklist *p=head;
while (P->next!=null) p=p->next;
Linklist *t= (linklist *) malloc (sizeof (linklist));
p->next=t;
t->data=data,t->val=val;
t->next=null;
return t;
} linklist *mergelist (linklist *a,linklist *b) {linklist *c= (linklist *) malloc (sizeof (linklist));
Linklist *pa=a->next,*pb=b->next,*pc=c;
while (Pa!=null&&pb!=null) {while (pa->data==0&&pa!=null) pa=pa->next;
while (Pb->data==0&&pb!=null) pb=pb->next;
if (pa->val<pb->val) pc->next=pa,pc=pa,pa=pa->next;
else if (pa->val>pb->val) pc->next=pb,pc=pb,pb=pb->next; else{pa->data+=pb->data;
if (pa->data!=0) pc->next=pa,pc=pa;
pa=pa->next,pb=pb->next;
}} if (Pa!=null) pc->next=pa;
else pc->next=pb;
return C;
} void Listprint (Linklist *head) {linklist *p=head->next;
while (P!=null) {printf ("%d%d\n", p->data,p->val);
p=p->next;
}} int main () {linklist *a=initlist (), *b=initlist ();
int na,nb;
int Da,va;
scanf ("%d", &na);
while (na--) {scanf ("%d%d", &da,&va);
Listinsert (A,DA,VA);
} scanf ("%d", &NB);
while (nb--) {scanf ("%d%d", &da,&va);
Listinsert (B,DA,VA);
} linklist *c=mergelist (A, b);
Listprint (c);
return 0;
}