栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

ZJU PTA 6-1 Add Two Polynomials

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ZJU PTA 6-1 Add Two Polynomials

6-1 Add Two Polynomials (10 point(s))

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;
  

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

Sample program of judge:
#include 
#include 
typedef struct Node *PtrToNode;
struct Node  {
    int Coefficient;
    int Exponent;
    PtrTonode Next;
};
typedef PtrTonode Polynomial;

Polynomial Read(); 
void Print( Polynomial p ); 
Polynomial Add( Polynomial a, Polynomial b );

int main()
{
    Polynomial a, b, s;
    a = Read();
    b = Read();
    s = Add(a, b);
    Print(s);
    return 0;
}



Sample Input:

4
3 4 -5 2 6 1 -2 0
3
5 20 -7 4 3 1

Sample Output:

5 20 -4 4 -5 2 9 1 -2 0
Polynomial Add( Polynomial a, Polynomial b )
{
    Polynomial s = a;// make s point to any dummy head
    Polynomial pa = a->Next, pb = b->Next;
    Polynomial cur = s;// as the cursor, in order to make s unchanged

    while (pa != NULL && pb != NULL) {// When any polynomial traversal is completed, we can stop
    // compare the exponents of each term of a and b
        if (pa->Exponent > pb->Exponent) {
            cur->Next = pa;
            pa = pa->Next;
            cur = cur->Next;
        }
        else if (pa->Exponent < pb->Exponent) {
            cur->Next = pb;
            pb = pb->Next;
            cur = cur->Next;
        }
        else {// if the exponent of pa equals to the exponent of pb
            pb->Coefficient += pa->Coefficient;// here I select the b as the base
            if (pb->Coefficient != 0) {
                cur->Next = pb;
                cur = cur->Next;
            }
            pa = pa->Next;
            pb = pb->Next;
        }
    }
    if (pa == NULL) {// If the pa has been traversed, let's point cur to psb
        cur->Next = pb;
    }
    else {// If the pb has been traversed, let's point cur to pa
        cur->Next = pa;
    }
    return s;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/703396.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号