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;
}