原题
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; /* Nodes are sorted in decreasing order of exponents.*/
The function
Add
is supposed to return a polynomial which is the sum ofa
andb
.
Sample program of judge:
#include <stdio.h> #include <stdlib.h> typedef struct Node *PtrToNode; struct Node { int Coefficient; int Exponent; PtrToNode Next; }; typedef PtrToNode Polynomial; Polynomial Read(); /* details omitted */ void Print( Polynomial p ); /* details omitted */ Polynomial Add( Polynomial a, Polynomial b ); int main() { Polynomial a, b, s; a = Read(); b = Read(); s = Add(a, b); Print(s); return 0; } /* Your function will be put here */
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
结尾无空行
题目分析
做这道题应该很多次了,但都是思路不太清楚的那种,今天刚好重温了何老师讲例题,采用了何老师讲的的思路,可能不太一致,但也算相似吧。主要是没办法自定函数,不然定义一个插入的函数会显得更加简洁。(我记得我最早做的时候大概是没有再创建一个新的node的链表而好像是创建了一个指针数组?,但显得很繁琐,感觉不如这个思路简洁,回头再看看,今天心情不好,懒得复盘了。)
注意给出的多项式链表形式带有头结点,为空的时候也带有一个头结点,此时head->Next=NULL
简要思路如下:
a不为NULL,b不为NULL时,进行a和b的指数比较
1. a的指数大,创建一个和a一致的node插入sum,下一个a
2. b的指数大,创建一个和b一致的node插入sum,下一个b
3. a和b的指数一样大,此时插入的node的系数为两者之和,若为0则不插入,其余情况插入。下一个a,下一个b
最后,a和b其中一个已经遍历完了,就将另一个剩下的node遍历插入sum
返回head
答案(AC)
Polynomial Add(Polynomial a, Polynomial b)
{
Polynomial sum;
sum = (Polynomial)malloc(sizeof(struct Node));
sum->Coefficient = 0;
sum->Exponent = 0;
sum->Next = NULL; //initial the head node
Polynomial head = sum;
a = a->Next;
b = b->Next;
while (a != NULL && b != NULL)
{
if (a->Exponent > b->Exponent)
{
Polynomial c = (Polynomial)malloc(sizeof(struct Node));
c->Exponent = a->Exponent;
c->Coefficient = a->Coefficient;
c->Next = NULL;
sum->Next = c;
sum = c;
a = a->Next;
}
else if (a->Exponent < b->Exponent)
{
Polynomial c = (Polynomial)malloc(sizeof(struct Node));
c->Exponent = b->Exponent;
c->Coefficient = b->Coefficient;
c->Next = NULL;
sum->Next = c;
sum = c;
b = b->Next;
}
else
{
Polynomial c = (Polynomial)malloc(sizeof(struct Node));
c->Exponent = b->Exponent;
c->Coefficient = b->Coefficient + a->Coefficient;
c->Next = NULL;
if (c->Coefficient != 0)
{
sum->Next = c;
sum = c;
}
else
{
free(c);
}
a = a->Next;
b = b->Next;
}
}
for (; a != NULL; a = a->Next)
{
Polynomial c = (Polynomial)malloc(sizeof(struct Node));
c->Exponent = a->Exponent;
c->Coefficient = a->Coefficient;
c->Next = NULL;
sum->Next = c;
sum = c;
}
for (; b != NULL; b = b->Next)
{
Polynomial c = (Polynomial)malloc(sizeof(struct Node));
c->Exponent = b->Exponent;
c->Coefficient = b->Coefficient;
c->Next = NULL;
sum->Next = c;
sum = c;
}
return head;
}
小tip:alt+shift+f 可格式重排美化代码