add函数中,在老师的基础上看同学的改法改了一个括号,在while的最后只要p != NULL,就让r->next指向p是没有问题的。q = NULL时自不必说,q != NULL时下一个while循环也会让r或者r->next指向正确的地方。
void add(LinkList pList1,LinkList pList2){
NodePtr p,q,r,s;
p = pList1->next;
q = pList2->next;
r = pList1;
free(pList2);
while((p != NULL) && (q != NULL)){
if(p->exponent < q->exponent){
r = p;
p = p->next;
}else if((p->exponent > q->exponent)){
r->next = q;
r = q;
q = q->next;
}else{
p->coefficient = p->coefficient + q->coefficient;
printf("The coefficient is: %d.n",p->coefficient);
if(p->coefficient == 0){
s = p;
p = p->next;
free(s);
}else{
r = p;
p = p->next;
}
s = q;
q = q->next;
free(s);
}
printf("p = %d,q = %d n",p,q);
if(p == NULL){
r->next = q;
}else {
r->next = p;
}
}
}
完整代码
#include#include typedef struct LinkNode{ int coefficient; int exponent; struct LinkNode *next; } *LinkList,*NodePtr; LinkList iniLinkList(){ LinkList Header = (LinkList)malloc(sizeof(struct LinkNode)); Header->coefficient = 0; Header->exponent = 0; Header->next = NULL; return Header; } void printList(LinkList pHeader){ NodePtr p = pHeader->next; while(p != NULL){ printf("%d * 10^%d +",p->coefficient,p->exponent); p = p->next; } printf("n"); } void appendElement(LinkList pHeader,int pCoefficient,int pExponent){ NodePtr p,q; q = (NodePtr)malloc(sizeof(struct LinkNode)); q->coefficient = pCoefficient; q->exponent = pExponent; q->next =NULL; p = pHeader; while(p->next != NULL){ p = p->next; } p->next = q; } void add(LinkList pList1,LinkList pList2){ NodePtr p,q,r,s; p = pList1->next; q = pList2->next; r = pList1; free(pList2); while((p != NULL) && (q != NULL)){ if(p->exponent < q->exponent){ r = p; p = p->next; }else if((p->exponent > q->exponent)){ r->next = q; r = q; q = q->next; }else{ p->coefficient = p->coefficient + q->coefficient; printf("The coefficient is: %d.n",p->coefficient); if(p->coefficient == 0){ s = p; p = p->next; free(s); }else{ r = p; p = p->next; } s = q; q = q->next; free(s); } printf("p = %d,q = %d n",p,q); if(p == NULL){ r->next = q; }else{ r->next = p; } } } void addTest(){ LinkList tempList1 = iniLinkList(); appendElement(tempList1,7,0); appendElement(tempList1, 3, 1); appendElement(tempList1, 9, 8); appendElement(tempList1, 5, 17); printList(tempList1); LinkList tempList2 = iniLinkList(); appendElement(tempList2, 8, 1); appendElement(tempList2, 22, 7); appendElement(tempList2, -9, 10); appendElement(tempList2, 5, 12); printList(tempList2); add(tempList1, tempList2); printList(tempList1); } int main(){ addTest(); return 0; }
运行结果
7 * 10^0 +3 * 10^1 +9 * 10^8 +5 * 10^17 + 8 * 10^1 +22 * 10^7 +-9 * 10^10 +5 * 10^12 + p = 7607440,q = 7629504 The coefficient is: 11. p = 7607472,q = 7629536 p = 7607472,q = 7629568 p = 7607504,q = 7629568 p = 7607504,q = 7629600 p = 7607504,q = 0 7 * 10^0 +11 * 10^1 +22 * 10^7 +9 * 10^8 +-9 * 10^10 +5 * 10^12 +5 * 10^17 +



