數據結構C語言描述——用單鏈表實現多項式的相加


#include <stdio.h>
#include <stdlib.h>

typedef DataType;
typedef struct Node2{
    DataType xishu;
    DataType zhisu;
    struct Node2 *Next;
}Node2;
typedef struct Node2* PNode2;

//多項式按照指數大小排序

void insertNewPoint_link(PNode2 head,PNode2 qNode){
    PNode2 p=head;
    while (p->Next!=NULL)
    {
        if (p->Next->zhisu>qNode->zhisu)
        {
            qNode->Next=p->Next;
            p->Next=qNode;
            break;
        }
        p=p->Next;
    }
    if (p->Next==NULL)
    {
        p->Next=qNode;

    }
}

//打印多項式
void printLinkeLink(PNode2 head){
    PNode2 temp=head->Next;

    while (temp!=NULL)
    {
        printf("%d %d",temp->xishu,temp->zhisu);
        printf("\n");
        temp=temp->Next;
    }
}


//多項式的加法計算
void add_poly(Node2 *pa,Node2 *pb){
    Node2 *p=pa->Next;
    Node2 *q=pb->Next;
    Node2 *pre=pa;
    Node2 *u;


    while (p!=NULL&&q!=NULL)
    {

        if (p->zhisu<q->zhisu)
        {
            pre=p;p=p->Next;
        } 
        else if(p->zhisu==q->zhisu)
        {
            float x=p->xishu+q->xishu;
            if (x!=0)
            {
                p->xishu=x;
                pre=p;
            } 
            else
            {
                pre->Next=p->Next;//指向下一個結點
                free(p);
            }
            p=pre->Next;
            u=q;
            q=q->Next;
            free(u);
        }
        else{
            u=q->Next;
            q->Next=p;
            pre->Next=q;
            pre=q;
            q=u;
        }
    }
    if (q)
    {
        pre->Next=q;
    }
    free(pb);
}


void main( ){

    int zhishu;
    float xishu;
    PNode2 head1=(PNode2)malloc(sizeof(struct Node2));
    PNode2 head2=(PNode2)malloc(sizeof(struct Node2));
    PNode2 tem=NULL;
    head1->Next=NULL;
    head2->Next=NULL;

    printf("輸入鏈表一的系數和指數,如:3,2 以0,0結束輸入:\n");
    scanf("%f,%d",&xishu,&zhishu);
    while (xishu!=0||zhishu!=0)
    {
        tem=(PNode2)malloc(sizeof(struct Node2));
        tem->xishu=xishu;
        tem->zhisu=zhishu;
        tem->Next=NULL;
        insertNewPoint_link(head1,tem);
        scanf("%f,%d",&xishu,&zhishu);
    }
    printf("鏈表一按指數升序排序后的多項式為:\n");
    printLinkeLink(head1);

    printf("\n");

    printf("輸入鏈表一的系數和指數,如:3,2 以0,0結束輸入:\n");
    scanf("%f,%d",&xishu,&zhishu);
    while (xishu!=0||zhishu!=0)
    {
        tem=(PNode2)malloc(sizeof(struct Node2));
        tem->xishu=xishu;
        tem->zhisu=zhishu;
        tem->Next=NULL;
        insertNewPoint_link(head2,tem);
        scanf("%f,%d",&xishu,&zhishu);
    }
    printf("鏈表二按指數升序排序后的多項式為:\n");
    printLinkeLink(head2);
    printf("\n");

    add_poly(head1,head2);
    printf("多項式相加后的結果為:\n");
    printLinkeLink(head1);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM