注册 登录
编程论坛 数据结构与算法

多项式加法怎么就错了

令狐少侠56 发布于 2015-10-26 10:27, 2146 次点击
原题,加法就出错了乘法还没写。因为加法函数注释掉才能像题目一样输入数据,否则输入N后得按enter,所以我就先将它注释掉了,
逻辑错了么?
我的方法:Poly1中的第k项与Poly2中的项依次扫描,匹配到求和,没匹配到直接将poly1的k项保存。

只有本站会员才能查看附件,请 登录

程序代码:
#include <stdio.h>
#include <stdlib.h>

typedef struct PolyNode *PtrPolyNode;
struct PolyNode //结构体类型声明忘记写分号
{
    int coef;
    int expon;
    struct PolyNode *next;
};


PtrPolyNode  CreatePolyList(int N)
{
    PtrPolyNode head;
    PtrPolyNode previous,current;

    int i;

    head=NULL;
   
    for( i=0 ; i<N ; i++)
    {
        current = ( PtrPolyNode )malloc( sizeof( struct PolyNode) ) ;
        current->next = NULL ;

        scanf("%d" , &(current->coef) ) ;   //忘记给系数和指数赋值
        scanf("%d" , &(current->expon) ) ;

        if(head==NULL)
            head = current ;
        else
            previous->next = current ;

            previous = current ;
    }
        return head;
}


/*PtrPolyNode Addition( PtrPolyNode Poly1 , PtrPolyNode Poly2 )
{
    PtrPolyNode head;
    PtrPolyNode current,previous;
   

    head=NULL;

    while( Poly1!=NULL )        
    {
        if( Poly1->expon==Poly2->expon && Poly2!=NULL ) //指数相同时系数相加,保存
        {
            current = ( PtrPolyNode ) malloc( sizeof(struct PolyNode) );

            current->next = NULL ;
            current->coef = Poly1->coef + Poly2->coef;
            current->expon = Poly1->expon;

            if(head=NULL)
                head=current;
            else
                previous->next=current;

            previous=current;

            Poly1=Poly1->next;
            Poly2=Poly2->next;/*由于指数按递减排序,故不需要将Poly1第k项与Poly2所有项比较,
                              Poly2高阶项匹配到以后直接从它的下一项开始扫描
*/
/*        }

        if( Poly1->expon != Poly2->expon && Poly2!=NULL )
        {
            Poly2=Poly2->next;    //与Poly2下一项比较
        }

        if( Poly2==NULL )        //Poly2中没有项能与Poly1第K项匹配,将其保存后进入k+1项的匹配
        {
            current = ( PtrPolyNode ) malloc( sizeof(struct PolyNode) );

            current->next = NULL ;
            current->coef = Poly1->coef;
            current->expon = Poly1->expon;

            if(head=NULL)
                head=current;
            else
                previous->next=current;

            previous=current;

            Poly1=Poly1->next;
        }
    }
   
    return head;
}
*/

void OutPut(PtrPolyNode head)
{

    while(head!=NULL)
    {
        printf("%d ",head->coef);
        printf("%d ",head->expon);
   
        head=head->next;
    }
    printf("\n");
}


int main()
{
    int N1,N2;        //非0项个数
    PtrPolyNode Poly1,Poly2,Poly3;

    scanf("%d",&N1);
    Poly1 = CreatePolyList( N1 ) ;

    scanf("%d",&N2);
    Poly2 = CreatePolyList( N2 ) ;

    OutPut( Poly1 );
    OutPut( Poly2 );

    //Poly3 = Addition( Poly1 , Poly2 );
   
//    OutPut( Poly3 );
}
2 回复
#2
令狐少侠562015-10-26 10:34
没人么

[此贴子已经被作者于2015-10-26 12:15编辑过]

#3
令狐少侠562015-10-26 11:25
回复 2楼 令狐少侠56
来人看看呗

[此贴子已经被作者于2015-10-26 12:15编辑过]

1