作业帮 > 综合 > 作业

多项式相加C语言

来源:学生作业帮 编辑:搜狗做题网作业帮 分类:综合作业 时间:2024/04/26 07:04:09
多项式相加C语言

多项式相加C语言
#include <stdio.h>
#include <malloc.h>

struct SLL
{
\x09// ax^r
\x09int a;
\x09int r;
\x09struct SLL* next;
};

struct SLL *add(struct SLL *head, int a, int r)
{
\x09struct SLL *t;
\x09struct SLL *tt;

\x09for(t=head, tt=NULL; t; tt = t, t = t->next) if(t->r <= r) break;

\x09if(!t)
\x09{
\x09\x09struct SLL *node = (struct SLL*)malloc(sizeof(struct SLL));
\x09\x09node->a = a;
\x09\x09node->r = r;
\x09\x09node->next = NULL;
\x09\x09if(!tt) return node;
\x09\x09tt->next = node;
\x09\x09return head;
\x09}

\x09if(t->r == r)
\x09{
\x09\x09t->a += a;
\x09\x09if(t->a == 0)
\x09\x09{
\x09\x09\x09if(!tt)
\x09\x09\x09{
\x09\x09\x09\x09tt = head;
\x09\x09\x09\x09head = head -> next;
\x09\x09\x09\x09free(tt);
\x09\x09\x09\x09return head;
\x09\x09\x09}
\x09\x09\x09tt->next = t->next;
\x09\x09\x09free(t);
\x09\x09\x09return head;
\x09\x09}
\x09}

\x09if(t->r < r)
\x09{
\x09\x09struct SLL *node = (struct SLL*)malloc(sizeof(struct SLL));
\x09\x09node->a = a;
\x09\x09node->r = r;
\x09\x09node->next = t;
\x09\x09if(!tt) return node;
\x09\x09tt->next = node;
\x09}
\x09
\x09return head;
}

void print(struct SLL *head)
{
\x09struct SLL *t = head;
\x09for(; t; t=t->next)
\x09{
\x09\x09printf("%d %d\n", t->a, t->r);
\x09}
}

int main()
{
\x09struct SLL *head = NULL;
\x09int m, n, a, r, i;
\x09scanf("%d%d", &m, &n);
\x09for(i=0; i<m+n; i++)
\x09{
\x09\x09scanf("%d %d", &a, &r);
\x09\x09head = add(head, a, r);
\x09}
\x09print(head);

\x09return 0;
}