两个多项式的相加&相乘
#include <stdio.h>
#include <stdlib.h>
typedef struct polynomial
{
int x[2];
struct polynomial *next;
}POL;
POL *creatlist (int n);
POL *addition (POL*head1, POL*head2,int n);
void output (POL *head);
POL *multiplication (POL*head1, POL*head2, int n, int m);
int main()
{
int n = 0, m = 0;
POL *head1, *head2;
printf ("请输入第1个多项式的项数!\n");
scanf ("%d", &n);
head1 = creatlist (n);
printf ("请输入第2个多项式的项数!\n");
scanf ("%d", &m);
head2 = creatlist (m);
printf ("相加结果为:\n");
output (addition (head1, head2, n));
printf ("相乘结果为:\n");
output (multiplication (head1, head2, n, m));
}
POL *creatlist (int n)
{
int i = 0;
POL *head, *pNew, *pMedian;
head = pMedian =(POL *) malloc (sizeof (POL));
for (i=0; i<n; i++)
{
pNew = (POL *) malloc (sizeof(POL));
printf ("请输入第%d项的系数!\n", i+1);
scanf ("%d", &pNew->x[0]);
printf ("请输入第%d项的幂数!\n", i+1);
scanf ("%d", &pNew->x[1]);
pMedian -> next = pNew;
pMedian = pNew;
}
pMedian -> next = NULL;
return head;
}
POL *addition (POL*head1, POL*head2, int n)
{
int i = 0, flag = 0;
POL *phead1, *phead2, *pn;
POL *nhead, *pNew, *pMedian;
phead1 = head1->next;
phead2 = head2->next;
nhead = pMedian =(POL *) malloc (sizeof (POL));
for (i=0; i<n; i++)
{
pNew = (POL *) malloc (sizeof(POL));
pNew -> x[0] = phead1->x[0];
pNew -> x[1] = phead1->x[1];
phead1 = phead1->next;
pMedian -> next = pNew;
pMedian = pNew;
}
pMedian -> next = NULL;
while (phead2 != NULL)
{
phead1 = head1 -> next;
pn = nhead -> next;
while (phead1 -> next != NULL)
{
if (phead2 -> x[1] == phead1 -> x[1])
{
pn->x[0] = phead1->x[0] + phead2->x[0];
break;
}
phead1 = phead1 -> next;
pn = pn -> next;
}
while (phead1 -> next == NULL)
{
if (phead2 -> x[1] == phead1 -> x[1])
{
pn -> x[0] = phead1 -> x[0] + phead2 -> x[0];
break;
}
else
{
for (i=0; i<flag; i++)
{
pn = pn -> next;
}
pNew = (POL *) malloc (sizeof(POL));
pn -> next = pNew;
pn = pNew;
pn -> x[0] = phead2 -> x[0];
pn -> x[1] = phead2 -> x[1];
pn -> next = NULL;
flag++;
break;
}
}
phead2 = phead2->next;
}
return nhead;
}
void output (POL *head)
{
POL* ph = head->next;
while (ph->next != NULL)
{
printf ("%d*x^%d+", ph->x[0], ph->x[1]);
ph = ph->next;
}
printf ("%d*x^%d\n", ph->x[0], ph->x[1]);
}
POL *multiplication (POL*head1, POL*head2, int n, int m)
{
int i = 0;
POL *phead1, *phead2, *pn;
POL *nhead, *pM, *pNew;
phead1 = head1 -> next;
phead2 = head2 -> next;
nhead = pM = (POL *) malloc (sizeof (POL));
while (phead1 != NULL)
{
phead2 = head2 -> next;
while (phead2 != NULL)
{
pNew = (POL *) malloc (sizeof(POL));
pM -> next = pNew;
pM = pNew;
pM -> x[0] = phead1 -> x[0]*phead2 -> x[0];
pM -> x[1] = phead1 -> x[1]+phead2 -> x[1];
pM -> next = NULL;
phead2 = phead2 -> next;
}
phead1 = phead1 -> next;
}
return nhead;
}
转载请注明原文地址:https://blackberry.8miu.com/read-6826.html