一元多項式加法計算問題

一元多項式加法計算問題

總體上來說一元多項式加法的計算問題難度一般並沒有什麼新的算法只是細節上需要注意,在加法上擴展的減法和乘除法都不算太難只需要在原代碼上進一步擴展就可以了
測試數據:
5,3 7,8 9,15 0,0
2,0 6,3 -7,8 0,0

3,1 5,3 7,8 9,15 0,0
2,0 6,3 -7,8 0,0

#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Node
{
    int factor;
    int power;
    Node *next;
}Linklist;

void Combine(Linklist *&A, Linklist *&B)
{
    Linklist *p = A, *t = p->next, *q = B->next, *s;
    while (q->next != NULL)
    {
        if (q->power == t->power)
        {
            int sum = t->factor + q->factor;
            if (sum == 0)
            {
                p->next = t->next;
                free(t);
                t = p->next;
            }
            else
            {
                t->factor = sum;
                p = p->next;
                t = t->next;
            }
            q = q->next;
        }
        else if (q->power < t->power)
        {
            s = (Linklist *)malloc(sizeof(Linklist));
            s->next = NULL;
            s->factor = q->factor;
            s->power = q->power;
            s->next = p->next;
            p->next = s;
            p = s;
            q = q->next;
            continue;
        }
        else if (q->power > t->power)
        {
            if (q->power > t->power&&t->next->next == NULL)
            {
                s = (Linklist *)malloc(sizeof(Linklist));
                s->next = NULL;
                s->factor = q->factor;
                s->power = q->power;
                s->next = t->next;
                t->next = s;
                q = q->next;
            }
            t = t->next;
        }
    }

}
void Displist(Linklist *L)
{
    Linklist *p = L->next;
    while (p->next->next != NULL)
    {
        cout << p->factor << 'x' << '^' << p->power;
        if (p->next->factor > 0)
            cout << '+';
        p = p->next;
    }
    cout << p->factor << 'x' << '^' << p->power;
}
int main()
{
    int i;
    char c;
    Linklist *A, *B, *t, *p, *q, *s;

    A = (Linklist *)malloc(sizeof(Linklist));
    A->next = NULL;
    p = A;
    while (1)
    {
        t = (Linklist *)malloc(sizeof(Linklist));
        cin >> t->factor >> c >> t->power;
        p->next = t;
        p = t;
        if (p->factor == 0 && p->power == 0)
            break;
    }
    p->next = NULL;

    B = (Linklist *)malloc(sizeof(Linklist));
    B->next = NULL;
    q = B;
    while (1)
    {
        s = (Linklist *)malloc(sizeof(Linklist));
        cin >> s->factor >> c >> s->power;
        q->next = s;
        q = s;
        if (q->factor == 0 && q->power == 0)
            break;
    }
    q->next = NULL;

    Combine(A, B);
    Displist(A);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章