习题3.6 用链表求多项式的加法

复制代码
/* 3.6 */
struct Node;
typedef struct Node * PtrToNode; 
typedef PtrToNode Position;
typedef PtrToNode List;

struct Node
{
    int coef;
    int exp;
    PtrToNode next;
};

Position
CreateList( void )
{
    int n = 0;
    PtrToNode p1,p2,head;
    p1 = malloc(sizeof(struct Node ) );
    if(P1 == NULL )
        Error("out of space ");
    scanf("%d %d",&p1->coe,&p2->exp);
    while( p1->coe != 0 )
    {
        if( ++n == 1)
            head = p1;
        else
            p2->Next = p1; 
        p2 = p1;
        p1 = malloc(sizeof(struct Node ))
        if( p1 == NULL )
            Error("out of space");
        scanf("%d %d",&p1->coe,&p1->exp);
    }
    return head;
}

Position
MakeEmpty()
{
    List L;
    L = malloc(sizeof(struct Node ));
    L->Next = NULL;
    return L;
}

void
Insert( Position p, int coe1, int exp1 )
{
    PtrToNode TmpCell;
    TmpCell = malloc( sizeof( struct Node ) );
    if( TmpCell == NULL )
        Error("out of space ");
    TmpCell->coe = coe1;
    TmpCell->exp = exp1;
    TmpCell->Next = p->Next;
    p->Next = TmpCell;
}
/* assume a header */
void
PrintList( List L )
{
    Position p;
    p = L->Next;
    while( p != NULL )
    {
        printf("%dX^%d",p->coe,p->exp);
        if( p->Next != NULL )
            printf("+");
        p = p->Next;
    }
}
Position
PolyAdd( void )
{
    Position L1Pos,L2Pos,LresPos;
    List Lres,L1,L2;
    
    L1 = CreateList();
    L2 = CreateList();
    
    Lres = MakeEmpty();
    LresPos = Lres;//因为Insert需要前一个位置,所以直接把表头的位置给了LresPos
    L1Pos = L1;
    L2Pos = L2;
    
    while(L1Pos != NULL && L2Pos != NULL )
    {
        if(L1Pos->exp > L2Pos->exp )
        {
            Insert( LresPos, L2Pos->coe, L2Pos->exp );
            L2Pos = next( L2, L2Pos );
        }
        else if( L1Pos->exp < L2Pos->exp )
        {
            Insert( LresPos, L1Pos->coe, L2Pos->exp );
            L2Pos = next( L2, L2Pos );
        }
        else
        {
            sum = L1Pos->coe+L2Pos->coe;
            if(sum != 0)
                Insert( LresPos, sum, L1pos->exp );
            L1Pos = next( L1, L1Pos );
            L2pos = next( L2, L2Pos );
        }
        LresPos = next( Lres, LresPos ); 
    }
    while( L1Pos !=NULL )
    {
        Insert( LresPos, L1Pos->coe, L1Pos->exp );
        LresPos = next( Lres, LresPos );
        L1Pos = next( L1, L1Pos );
    }
    while( L2Pos !=NULL )
    {
        Insert( LresPos, L2Pos->coe, L2Pos->exp );
        LresPos = next( Lres, LresPos );
        L1Pos = next( L2, L2Pos );
    }
    PrintList(Lres);
}
View Code
复制代码

思路同3.5,将次数低的结点Insert进Lres,如果有相等的,就把系数加起来,Insert一个结点

当然可能L1或是L2还有些结点由于次数偏高没遍历到,所以继续补充

这里随时增加结点的方式是Insert,结点增加后记得,更新Lres的末地址,才能达到随时增加结点效果

 

posted @   Gabyler  阅读(284)  评论(2编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示