当前位置:网站首页>6-40 constructing ordered sparse polynomial chained storage

6-40 constructing ordered sparse polynomial chained storage

2022-06-22 09:36:00 Xia ~ Chen

This problem constructs a chain stored procedure of ordered sparse polynomials , The input polynomial has two terms : Coefficients and exponents .

Be careful : The input exponent is unordered . Please save polynomials in chained storage .

Output in the order of the exponent from small to large .

To simplify the construction of linked list , The default construction linked list is the supervised single linked list .

Function interface definition :

ptr creat();

creat Function is to construct linked list .

Sample referee test procedure :

#include <stdio.h>
#include <malloc.h>


typedef struct node
{
    float ceof;
    int exp;
    struct node *next;
}node,*ptr;

ptr creat();

void output(ptr h)
{
    ptr p;
    p=h->next;
    while(p!=NULL)
    {
        printf("%+.1fx^%d",p->ceof,p->exp);
        p=p->next;
    }
    printf("\n");
}

int main()
{
    ptr head;
    head=creat();
    output(head);
    return 0;
}

/*  Please fill in the answer here  */

sample input :

100.3  10
90  5
18  92
21.8  2
-19  0
0  0

No blank lines at the end

sample output :

-19.0x^0+21.8x^2+90.0x^5+100.3x^10+18.0x^92

  Ideas : Construct a chain storage structure , Then make the input data orderly according to the index , Here I offer two ideas : One is that we sort while inputting , One is to sort after we have constructed it , Below I provide the algorithm of sorting while inputting

, Code up

ptr creat()
{
    ptr p;
    p = (ptr)malloc(sizeof(node));// Application node space 
    node* q, * pre, * s;
    p ->next = NULL;// The tail node is empty 
    
    while(1)
    {
        
        s = (ptr)malloc(sizeof(node));
        scanf("%f %d", &s->ceof, &s->exp);// The input values 
        pre = p;
        q = p -> next;
        while (q && q->exp < s->exp)// Edge input edge comparison 
        {
            pre = q;
            q = q->next;

        }
        if(s->ceof==0)// Cycle end condition , That is, the input value and index are 0
            break;
        s->next = q;
        pre->next = s;
        
        
            
    }

}

原网站

版权声明
本文为[Xia ~ Chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202220522574244.html