作业帮 > 综合 > 作业

在C语言实现的一元多项式的相加操作中,怎样同时实现合并一个多项式中的同类项?

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/29 09:17:37
在C语言实现的一元多项式的相加操作中,怎样同时实现合并一个多项式中的同类项?
abcddd_1234 06:50:38
#include
#include
typedef struct Polynode
{
int coef;
int exp;
struct Polynode *next;
} Polynode;
Polynode* polycreate(/*Polynode *head*/)
{
Polynode *h,*rear,*s,*temp;
int c,e;
h=(Polynode *)malloc(sizeof(Polynode)); /*建立多项式的头结点*/
h->next = NULL;
scanf("%d%d",&c,&e);/*键入多项式的系数和指数项*/
while(c!=0) /*若c=0,则代表多项式的输入结束*/
{
s=(Polynode*)malloc(sizeof(Polynode)); /*申请新的结点*/
s->coef=c ;
s->exp=e ;
rear = h;//rear不再指向尾节点,而是从头结点开始遍历
temp = rear->next;
while(temp!=NULL && temp->exp expexp>e,否则直到链表结尾
if(rear->exp==temp->exp) {rear->coef+temp->coef;}//此句为合并同类项
else{ rear = temp;
temp = rear->next;
}}
s->next = temp;//插入
rear->next = s;
scanf("%d%d",&c,&e);
}
return(h);
}
void polylist_add(Polynode *head1,Polynode *head2)
{
int sum;Polynode *temp;
Polynode *p=head1->next,*q=head2->next,*r=head1;
while(p!=NULL&&q!=NULL)
{
if(p->expexp) {r->next=p;r=r->next;p=p->next;}
else if(p->exp>q->exp) {r->next=q;r=r->next;q=q->next;}
else {sum=(p->coef)+(q->coef);
if(sum!=0) {p->coef=sum;r->next=p;r=r->next;p=p->next;temp=q;q=q->next;free(temp);}
else {temp=p->next;free(p);p=temp;
temp=q->next;free(q);q=temp;}
}
if(p!=NULL) r->next=p;
else
r->next=q;
}}
void printf_list(Polynode *head)
{
Polynode *p=head->next;
while(p)
{printf("%dx^%d",p->coef,p->exp);if(p->next)
printf("+");p=p->next;}
}
int main()
{
Polynode *head1,*head2;
//clrscr();
head1=polycreate(/*head1*/);
head2=polycreate(/*head2*/);
printf_list(head1);
printf("\n");
printf_list(head2);
printf("\n");
polylist_add(head1,head2);
printf_list(head1);
getchar();
getchar();
return 0;
}
为什么没有实现合并一个多项式中同类项的操作啊?
Polynode* polycreate( /* Polynode *head */ ) {
\x05Polynode *h,*rear,*s,*temp;
\x05int c,e;
\x05h = (Polynode*)malloc(sizeof(Polynode)); /* 建立多项式的头结点 */
\x05h->next = NULL;
\x05scanf("%d%d",&c,&e); /* 键入多项式的系数和指数项 */
\x05while (c != 0) /* 若c=0,则代表多项式的输入结束 */ {
\x05\x05rear = h; // rear不再指向尾节点,而是从头结点开始遍历
\x05\x05temp = rear->next;
\x05\x05while (temp != NULL && temp->exp < e) {
\x05\x05\x05rear = temp;
\x05\x05\x05temp = rear->next;
\x05\x05}
\x05\x05if(temp!=NULL&&temp->exp==e)/*如果上面寻找退出时,temp不为空且它的指数和输入指数相同*/
\x05\x05{
\x05\x05\x05temp->coef+=c;
\x05\x05}
\x05\x05else/*这是一个当前多项式没有出现的指数项,新建节点保存*/
\x05\x05{
\x05\x05\x05s = (Polynode*)malloc(sizeof(Polynode)); /* 申请新的结点 */
\x05\x05\x05s->coef = c;
\x05\x05\x05s->exp = e;
\x05\x05\x05s->next = rear->next; // 插入
\x05\x05\x05rear->next = s;
\x05\x05}
\x05\x05scanf("%d%d",&c,&e);
\x05}
\x05return(h);
}
建议scanf("%d%d",&c,&e); 这里分成2句,如果c==0,直接退出录入