a+b polynomial

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

typedef struct node* Node;

struct node{
    int exp;
    float coe;
    Node next;
};

Node input(void);
Node add(Node p1,Node p2);
void attach(int e,float c,Node *rear);
void print(Node p);

int main()
{
    Node P1,P2,P3;
    
    printf("there2
");
    P1 = input();
    print(P1);
    printf("there3
");
    P2 = input();
    print(P2);
    printf("there1
");
    P3 = add(P1,P2);
    printf("there4
");
    print(P3);
    system( "PAUSE ");
    return 0;
}

Node input(void)
{
    int N,i;
    int tempe;
    float tempc;
    Node p,p1;
    Node temp;
    
    p = (Node)malloc(sizeof(struct node));
    p->next = NULL;
    p1 = p;
    
    scanf("%d ",&N);
    
    for(i=0;i<N;i++)
    {
        scanf("%d %f ",&tempe,&tempc);
        p1->next = (Node)malloc(sizeof(struct node));
        p1 = p1->next;
        p1->exp = tempe;
        p1->coe = tempc;
        p1->next = NULL;
    }
    
    temp = p;
    p = p->next;
    free(temp);
    
    return p;
}

Node add(Node P1,Node P2)
{
    Node p, rear,temp;
    
    p = (Node)malloc(sizeof(struct node));
    p->next = NULL;
    rear = p;
    printf("there5
");
    while(P1 && P2)
    {
        printf("there10
");
        if(P1->exp > P2->exp)
        {
            attach(P1->exp,P1->coe,&rear);
            P1 = P1->next;
        }
        else if(P1->exp < P2->exp)
        {
            printf("there8
");
            attach(P2->exp,P2->coe,&rear);
            printf("there9
");
            P2 = P2->next;
        }
        else
        {
            if((P1->coe+P2->coe))                //浮点数为0的判断,需注意
                attach(P2->exp,P1->coe+P2->coe,&rear);
            P2 = P2->next;
            P1 = P1->next;
        }
    }
    printf("there7
");
    while(P1)
    {
        printf("there11
");
        attach(P1->exp,P1->coe,&rear);
        P1 = P1->next;
    }
    while(P2)
    {
        printf("there12
");
        attach(P2->exp,P2->coe,&rear);
        P2 = P2->next;
    }
    
    temp = p;
    p = p->next;
    free(temp);
    printf("there6
");
    return p;
}

void attach(int e,float c,Node *rear)
{
    Node temp;
    temp = (Node)malloc(sizeof(struct node));
    temp->exp = e;
    temp->next = NULL;
    temp->coe = c;
    
    ((*rear)->next) = temp;
    (*rear) = temp;
}

void print(Node p)
{
    int cnt = 0,i = 0;
    Node temp;
    
    temp = p;
    
    while(temp)
    {
        cnt++;
        temp = temp->next;
    }
    printf("%d ",&cnt);
    
    for(;i<cnt-1;i++)
    {
        printf("%d ",&(p->exp));
        printf("%f ",&(p->coe));
        p = p->next;
    }
    printf("%d ",&(p->exp));
    printf("%f",&(p->coe));
}
原文地址:https://www.cnblogs.com/katyusha1/p/12660556.html