Escribe una función para sumar dos polinomios. No destruya la entrada. Utilice una implementación de lista vinculada con un nodo principal ficticio. Nota: El polinomio cero está representado por una lista vacía con solo el nodo principal ficticio.
Formato de funciones:
Polynomial Add( Polynomial a, Polynomial b );
where Polynomial is defined as the following:
typedef struct Node *PtrToNode;
struct Node {
int Coefficient;
int Exponent;
PtrToNode Next;
};
typedef PtrToNode Polynomial;
/* Nodes are sorted in decreasing order of exponents.*/
Se supone que la función Sumar devuelve un polinomio que es la suma de ay b.
Programa de muestra de juez:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node *PtrToNode;
struct Node {
int Coefficient;
int Exponent;
PtrToNode Next;
};
typedef PtrToNode Polynomial;
Polynomial Read(); /* details omitted */
void Print( Polynomial p ); /* details omitted */
Polynomial Add( Polynomial a, Polynomial b );
int main()
{
Polynomial a, b, s;
a = Read();
b = Read();
s = Add(a, b);
Print(s);
return 0;
}
/* Your function will be put here */
Entrada de muestra:
4
3 4-5 2 6 1-2 0
3
5 20-7 4 3 1
Salida de muestra:
5 20-4 4-5 2 9 1-2 0
① Una lista vinculada con un nodo principal, donde los datos se almacenan realmente es el siguiente nodo
② Los nodos cuya suma de coeficientes es 0 se omiten y no se consideran nodos en la lista de resultados.
③ El nodo temporal tmp debe volver a aplicarse cada vez que se encuentre en el bucle
Polynomial Add( Polynomial a, Polynomial b ){
Polynomial p = a->Next;
Polynomial q = b->Next;
Polynomial res = (Polynomial)malloc(sizeof(struct Node));
Polynomial head = res;
while(p&&q){
Polynomial tmp = (Polynomial)malloc(sizeof(struct Node));
if(p->Exponent==q->Exponent){
tmp->Exponent = p->Exponent;
tmp->Coefficient = p->Coefficient + q->Coefficient;
p = p->Next;
q = q->Next;
if(tmp->Coefficient!=0){
res->Next = tmp;
res = tmp;
}
}
else if(p->Exponent<q->Exponent){
tmp->Exponent = q->Exponent;
tmp->Coefficient = q->Coefficient;
q = q->Next;
res->Next = tmp;
res = tmp;
}
else{
tmp->Exponent = p->Exponent;
tmp->Coefficient = p->Coefficient;
p = p->Next;
res->Next = tmp;
res = tmp;
}
}
if(p)
res->Next = p;
if(q)
res->Next = q;
return head;
}