多项式相加C语言
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/22 16:16:07
多项式相加C语言
多项式相加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;
}