#include <cstdio>
#include <iostream>

using namespace std;

struct list {
    int a;
    int b;
    list *next;
};

void cteatList(list *&head)
{
    head = new list;
    head->next = NULL;
    list *pCur = head;

    int a, b;
    while (scanf("%d,%d", &a, &b))
    {
        if (a == 0 && b == 0)
        {
            break;
        }
        list *pm = new list;
        pm->next = NULL;
        pm->a = a;
        pm->b = b;
        pCur->next = pm;
        pCur = pm;
    }
}

void destoryList(list *head)
{
    list *pCur = head;

    while (pCur != NULL)
    {
        list *pTemp = pCur->next;
        delete pCur;
        pCur = pTemp;
    }
}


void add(list *&n1, list *&n2)
{
    list *p1 = n1->next;
    list *p2 = n2->next;
    list *pre = n1;  //n2加到n1去 
    while (p1 != NULL && p2 != NULL)
    {
        if (p1->b == p2->b)
        {
            p1->a += p2->a;
            list *temp = p2;
            p2 = p2->next;
            delete temp;
            if (p1->a == 0)
            {
                pre->next = p1->next;
                p1 = pre->next;
            }
        }
        else if (p1->b > p2->b)
        {
            list *temp = p2->next;
            p2->next = p1;
            pre->next = p2;
            pre = p2;
            p2 = temp;
        }
        else
        {
            p1 = p1->next;
            pre = pre->next;
        }
    }
    if (n1 == NULL)
    {
        pre->next = n2;
    }
}


void print(list *head)
{
    list *temp = head->next;
    printf("%dx^%d", temp->a, temp->b);
    temp = temp->next;
    while (temp != NULL)
    {
        printf("+%dx^%d", temp->a, temp->b);
        temp = temp->next;
    }
}

int main()
{
    list *n1;
    list *n2;
    cteatList(n1);
    cteatList(n2);
    add(n1, n2);
    print(n1);
    destoryList(n1);
    return 0;
}

另一篇简单解法:
非常规解法(数组)

最后修改:2019 年 04 月 13 日
如果觉得我的文章对你有用,请随意赞赏