3-1 一元多项式求导

标准解答:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 typedef struct PolyNode *Polynomial;
 5 struct PolyNode {
 6     int coef;
 7     int expon;
 8     Polynomial Next;
 9 };
10 void Attach(int c, int e, Polynomial *pRear)
11 {
12     Polynomial P;
13     P = (Polynomial)malloc(sizeof(struct PolyNode));    //申请一个新结点
14     P->coef = c;    //对新结点赋值
15     P->expon = e;
16     P->Next = NULL;
17     (*pRear)->Next = P;
18     *pRear = P;
19 }
20 
21 Polynomial ReadPoly()
22 {
23     //读入并建立多项式
24     Polynomial P, Rear, t;
25     int c, e;
26     //为了程序处理方便起见,先构造一个链表空节点
27     P = (Polynomial)malloc(sizeof(struct PolyNode));
28     Rear = P;
29     while (scanf_s("%d %d", &c, &e) != EOF)
30         Attach(c, e, &Rear);
31 
32     //删除头结点
33     t = P;
34     P = P->Next;
35     free(t);
36     return P;
37 }
38 
39 Polynomial PolyDifferentiation(Polynomial P)
40 {
41     //求多项式的导数函数,返回结果多项式
42     Polynomial P1, P2;
43     P2 = P, P1 = NULL;        //P1总指向p2的前一项
44     while (P2 && P2->expon)
45     {
46         P2->coef = P2->coef * P2->expon;
47         P2->expon--;
48         P1 = P2;
49         P2 = P2->Next;
50     }
51     if (P2)        //如果多项式中存在常数项
52     {
53         if (P1) {            //如果常数项不是第一项,也就是P1 != NULL
54             free(P2);
55             P1->Next = NULL;
56         }
57         else        //P1 = NULL, 也就是说常数项是第一项
58         {
59             P2->coef = 0;
60         }
61     }
62     return P;
63 }
64 
65 void PrintPoly(Polynomial P)
66 {
67     //输出多项式
68     int flag = 0;
69     while (P)
70     {
71         if (!flag)
72             flag = 1;
73         else
74             printf(" ");
75         printf("%d %d", P->coef, P->expon);
76         P = P->Next;
77     }
78     printf("\n");
79 }
80 
81 int main()
82 {
83     Polynomial P;
84     P = ReadPoly();
85     P = PolyDifferentiation(P);            //求导函数
86     PrintPoly(P);    //输出多项式
87 
88     return 0;
89 }

粗糙解答:

 1 int main()
 2 {
 3     int coef, expon;
 4     Polynomial front, rear, temp;
 5     front = rear = (Polynomial)malloc(sizeof(struct PolyNode));
 6     while (scanf_s("%d %d", &coef, &expon) != EOF)
 7     {
 8         temp = (Polynomial)malloc(sizeof(struct PolyNode));
 9         temp -> coef = coef * expon;
10         temp -> expon = expon -1;
11         temp ->Next = NULL;
12         rear->Next = temp;
13         rear = temp;
14     }
15     if (front->Next->expon == -1)    //如果常数项是第一项
16         printf("0 0\n");
17     else
18     {
19         for (temp = front->Next; temp->Next; temp = temp->Next)
20             printf("%d %d ", temp->coef, temp->expon);
21         if (temp->expon != -1)
22             printf("%d %d\n", temp->coef, temp->expon);    //并没有将(0, -1)的结点删去,只是没有输出而已
23     }    
24     return 0;
25 }

 

上一篇:Java进行N阶函数拟合


下一篇:Java之生产者-消费者模式