第三章作業1-棧-計算機17級 7-16 一元多項式求導 (20 分)
阿新 • • 發佈:2018-12-14
7-16 一元多項式求導 (20 分)
設計函式求一元多項式的導數。
輸入格式:
以指數遞降方式輸入多項式非零項係數和指數(絕對值均為不超過1000的整數)。數字間以空格分隔。
輸出格式:
以與輸入相同的格式輸出導數多項式非零項的係數和指數。數字間以空格分隔,但結尾不能有多餘空格。
輸入樣例:
3 4 -5 2 6 1 -2 0
輸出樣例:
12 3 -10 1 6 0
方法一:直接模擬法
#include <iostream> using namespace std; int main() { int m,n; int flag = 1; while(cin>>m>>n) { if(n!=0) { if(!flag) { cout<<" "; } cout<<m*n<<" "<<n-1; flag = 0; } else continue; } if(flag) cout<<0<<" "<<0; }
方法二:連結串列法
#include <bits/stdc++.h> typedef int Status; typedef int ElemType; using namespace std; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef struct LNode{ ElemType coef;//係數 ElemType index;//指數 struct LNode *next; }LNode,*LinkList; Status CreateList_CL(LinkList &L); void qiudao(LinkList &L1,LinkList L2); void ListPrint(LinkList &L); int main() { LinkList A,B; //cout<<0; A=(LinkList)malloc(sizeof(LNode)); if(A==NULL) return OVERFLOW; A->next=NULL; CreateList_CL(A); //cout<<0<<endl;; //CreateList_CL(B); B=(LinkList)malloc(sizeof(LNode)); if(B==NULL) return OVERFLOW; B->next=NULL; qiudao(A,B); ListPrint(B); } Status CreateList_CL(LinkList &L) { LinkList p,rear; rear = L; //L = (LinkList)malloc(sizeof(LNode)); //if(!L) //exit(OVERFLOW); //L->next = NULL; int m,n; while(cin>>m>>n) { p = (LinkList)malloc(sizeof(LNode)); if(!p) exit(OVERFLOW); p->coef = m; p->index = n; rear->next = p;//尾部插入 rear = p; } rear->next = NULL; return OK; } void qiudao(LinkList &L1,LinkList L2) { LinkList p = L1->next,q = L2; int a,b; while(p) { a = (p->coef)*(p->index); b = (p->index) - 1; LinkList tmp; tmp = (LinkList)malloc(sizeof(LNode)); if(!tmp) exit(OVERFLOW); tmp->coef = a; tmp->index = b; tmp->next = NULL; if(a!=0) { q->next = tmp; q = q->next; } p = p->next; } } void ListPrint(LinkList &L) { LNode *p; p=L->next; if(p==NULL) cout<<0<<" "<<0; while(p) { if(p->next==NULL) cout<<(p->coef)<<" "<<(p->index); else cout<<(p->coef)<<" "<<(p->index)<<" "; p=p->next; } cout<<endl; }