4-3-Add Two Polynomials

来源:互联网 发布:大学java期末考试试题 编辑:程序博客网 时间:2024/06/06 12:44
4-3 Add Two Polynomials

Write a function to add two polynomials. Do not destroy the input. Use a linked list implementation with a dummy head node. Note: The zero polynomial is represented by an empty list with only the dummy head node.

Format of functions:

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.*/

The function Add is supposed to return a polynomial which is the sum of a and b.

Sample program of judge:

#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 */

Sample Input:

43 4 -5 2 6 1 -2 035 20 -7 4 3 1

Sample Output:

5 20 -4 4 -5 2 9 1 -2 0
Polynomial Add( Polynomial a, Polynomial b ){Polynomial c, p;c = (Polynomial)malloc(sizeof(struct Node));c->Next = NULL;a = a->Next;b = b->Next;p = c;while(a!=NULL&&b!=NULL){if(a->Exponent < b->Exponent){p->Next = b;b = b->Next;p = p->Next;p->Next = NULL;}else if(a->Exponent > b->Exponent){p->Next = a;a = a->Next;p = p->Next;p->Next = NULL;}else{Polynomial t;t = (Polynomial)malloc(sizeof(struct Node));t->Coefficient = a->Coefficient + b->Coefficient;t->Exponent = a->Exponent;t->Next = NULL;if(t->Coefficient != 0){p->Next = t;p = p->Next;}a = a->Next;b = b->Next;}}while(a!=NULL){p->Next = a;p = p->Next;a = a->Next;}while(b!=NULL){p->Next = b;p = p->Next;b = b->Next;}p->Next = NULL;return c;}
1 0
原创粉丝点击