A solution for Project Four
Below is the listing for a possible solution to the project.
/* MCS 275 Project Four: Sorting Monomials */
#include <stdio.h>
#include <stdlib.h>
typedef struct poly POLY;
struct poly
{
float coefficient;
int degree;
POLY *tail;
};
POLY *read ();
/* reads a list of monomials given by the user */
void print ( POLY *p );
/* prints the monomials on screen */
POLY *smallest ( POLY *p, int sd );
/* returns the monomial in p of smallest degree strictly larger than sd */
POLY *sort ( POLY *p );
/* sorts the monomials in decreasing degrees */
int main()
{
POLY *p;
printf("Reading a list of monomials.\n");
p = read();
printf("The list of monomials : \n");
print(p);
p = sort(p);
printf("The sorted list of monomials : \n");
print(p);
return 0;
}
POLY* read ()
{
POLY *p;
float cff;
int deg;
p = NULL;
printf("Give coefficient (0.0 to stop) : ");
scanf("%f", &cff);
if (cff != 0.0)
{
printf("Give the degree of the monomial : ");
scanf("%d", °);
p = (POLY*)calloc(1,sizeof(POLY));
p->coefficient = cff;
p->degree = deg;
p->tail = read();
}
return p;
}
void print ( POLY *p )
{
if (p != NULL)
{
printf("%f*x^%d\n", p->coefficient, p->degree);
print(p->tail);
}
}
POLY *smallest ( POLY *p, int sd )
{
POLY *ptr,*minmon;
int min = sd;
minmon = NULL;
for (ptr = p; ptr != NULL; ptr = ptr->tail)
{
if (ptr->degree > sd)
{
if (min == sd)
{
min = ptr->degree;
minmon = ptr;
}
else if (ptr->degree < min)
{
min = ptr->degree;
minmon = ptr;
}
}
}
return minmon;
}
POLY *sort ( POLY *p )
{
POLY *sp;
int smalldeg = -1;
POLY *smallmon,*newmon;
if (p == NULL)
sp = NULL;
else if (p->tail == NULL)
sp = p;
else
{
sp = NULL;
smallmon = smallest(p,smalldeg);
while (smallmon != NULL)
{
newmon = (POLY*)calloc(1,sizeof(POLY));
newmon->coefficient = smallmon->coefficient;
newmon->degree = smallmon->degree;
newmon->tail = sp;
sp = newmon;
smallmon = smallest(p,smallmon->degree);
}
}
return sp;
}