疑惑,可以帮我分析一下为什么会这样?
写了一个简单的动态链表,但是在执行的时候虽然提示输入第二个多项式,但实际上相当于无效输入,根本不显示多项式二的数据,如图:
程序代码:
#include <stdio.h> #include <stdlib.h> typedef struct ploy { double coef; int expn; struct ploy *next; }Linklist; int n = 0; Linklist *creat() { Linklist *head, *p1, *p2; p1 = p2 = (Linklist *)malloc(sizeof(Linklist *)); head = NULL; scanf("%lf %d", &p1->coef, &p1->expn); while (p1->coef != 0) { n++; if (n == 1) head = p1; else p2->next = p1; p2 = p1; p1 = (Linklist *)malloc(sizeof(Linklist *)); scanf("%lf %d", &p1->coef, &p1->expn); } p2->next = NULL; return head; } void visit(Linklist *temp) { Linklist *ploy; int i = 0; ploy = temp; while (ploy) { if (i == 0) { printf("%3.2lf*X^%d", ploy->coef, ploy->expn); ploy = ploy->next; i = 1; } else if (ploy->coef<0) { printf("%3.2lf*X^%d", ploy->coef, ploy->expn); ploy = ploy->next; } else if (ploy->coef>0) { printf("+%3.2lf*X^%d", ploy->coef, ploy->expn); ploy = ploy->next; } } } Linklist *sum(Linklist *ploy1, Linklist *ploy2) { Linklist *ptr1, *ptr2, *temp, *head; temp = (Linklist *)malloc(sizeof(Linklist *)); head = ptr1 = ploy1; ptr2 = ploy2; while (ptr1 != NULL&&ptr2 !=NULL) { if (ptr1->expn == ptr2->expn) { ptr1->coef = ptr1->coef + ptr2->coef; ptr1 = ptr1->next; ptr2 = ptr2->next; } else if (ptr1->expn < ptr2->expn) { ptr1 = ptr1->next; } else if (ptr1->expn > ptr2->expn) { temp->coef = ptr2->coef; temp->expn = ptr2->expn; temp->next = ptr1->next; ptr1->next = temp; ptr2 = ptr2->next; } } return head; } int main() { Linklist *L, *H, *result; printf("输入多项式一:\n"); L = creat(); printf("输入多项式二:\n"); H = creat(); printf("输入的数据为:\n"); visit(L); visit(H); result = sum (L, H); printf("结果:\n"); visit(result); printf("\n"); return 0; }