在多项式相加中一共有三种情况,p的指数大于q、q的指数大于p、相等。在相等时,又涉及到系数之和是否为零的情况,接下来将对多项式相加,并且连接做一个分布展示。
第一步,定义链表
typedef struct LinkNode {
int coefficient;
int exponent;
struct LinkNode* next;
}*LinkList,*NodePtr;
第二步,初始化
LinkList initLinkList() {
LinkList tempHeader = (LinkList)malloc(sizeof(struct LinkNode));
tempHeader->coefficient = 0;
tempHeader->exponent = 0;
tempHeader->next = NULL;
return tempHeader;
}//of initLinkList
第三步,打印
void printList(LinkList paraHeader) {
NodePtr p = paraHeader->next;
while (p != NULL) {
printf("%d *10^%d+", p->coefficient, p->exponent);
p = p->next;
}//of while
printf("\r\n");
}//of printList
第四步,节点打印
void printNode(NodePtr paraPtr, char paraChar) {
if (paraPtr == NULL) {
printf("NULL\r\n");
}
else {
printf("The element of %c is (%d * %d^%d)\r\n", paraChar,paraPtr->coefficient,paraPtr->exponent);
}
}//of printNode
第五步,元素添加
void appenfElement(LinkList paraHeader, int paraCoefficient,int paraExponent)
{
NodePtr p, q;
//step1.Construct a new node
q = (NodePtr)malloc(sizaof(struct LinkNode));
q->coefficient = paraCoefficient;
q->exponent = paraExponent;
q->next = NULL;
//step2,Search to the tail.
p = paraHeader;
while (p->next != NULL) {
p = p->next;
}//of while.
//step3.Now add/link
p->next = q;
}//of appendElement
第六步,链表连接
void add(NodePtr paraList1, NodePtr paraList2) {
NodePtr p, q, r, s;
//step1.Search to the position
p = paraList1->next;
printNode(p, 'p');
q = paraList2->next;
printNode(p, 'p');
r = paraList1;
printNode(r, 'r');
while (p != NUll && q != NULL) {
if (p->exponent < q->exponent) {
//Link the current node of the first list
printf("case 1\r\n");
r = p;
printNode(r.'r');
p = p->next;
printNode(p, 'p');
}
else if (p->exponent > q->exponent) {
printf("case 2\r\n");
//Link the current node of the second list
r->next = q;
r = q;
printNode(r, 'r');
q = q->next;
printNode(q, 'q');
}
else {
printf("case 3\r\n");
//change the current node of the first list
p->coefficient = p->coefficient + q->coefficient;
printf("The coefficient is %d.\r\n", p->coefficient);
if (p->coefficient == 0) {
printf("case 3.1");
s = p;
p = p->next;
printNode(p, 'p');
free(s);
}
else {
printf("case 3.2\r\n");
r = p;
printNode(r, 'r');
p = p->next;
printNode(p, 'p');
}
s = q;
q = q->next;
free(s);
}
printf("p=%ld,q=%ld\r\n", p, q);
}
printf("End of while.\r\n");
if (p == NULL) {
r->next = q;
}
else {
r->next = p;
}
printf("Addition ends.\r\n");
}
第六步,测试
void additionTest() {
LinkList tempList1 = initLinkList();
appendElement(tempList1, 7, 0);
appendElement(tempList1, 3, 1);
appendElement(tempList1, 9, 8);
appendElement(tempList1, 5, 17);
printList(tempList1);
LinkList tempList2 = initLinkList();
appendElement(tempList2, 8, 1);
appendElement(tempList2, 22, 7);
appendElement(tempList2, -9, 8);
printList(tempList2);
add(tempList1, tempList2);
printList(tempList1);
}
多项式的加和,最主要是需要列清楚所涉及的所有情况,以及测试。测试可以有白盒测试和黑盒测试。在进行黑盒测试检测时,要注意用例要有边界情况和普遍情况。