level 7
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node* ptr;
struct node
{
int coe;
int exp;
ptr next;
};
ptr create(void);
void add(ptr s, int x, int y);
int* arr(ptr s, int x, int y);
void print(ptr s);
int main(void)
{
ptr s1;
s1 = create();
add(s1, 1, 2);
add(s1, 3, 2);
add(s1, 1, 3);
add(s1, 1, 0);
print(s1);
return 0;
}
ptr create(void)
{
ptr s;
s = (ptr)malloc(sizeof(struct node));
if (s == NULL)
{
printf("create fail\n");
return 0;
}
s->next = NULL;
return s;
}
int num(ptr s)
{
int NUM;
s = s->next;
while (s != NULL)
{
NUM++;
}
return NUM;
}
int* arr(ptr s, int x ,int y)
{
int* ar;
int NUM;
NUM = num(s);
ar = (int*)malloc(sizeof(int) * NUM);
for (int i = 0; i < NUM; i++)
{
ar[i] = y;
}
return ar;
}
void add(ptr s, int x, int y)
{
ptr value;
value = (ptr)malloc(sizeof(struct node));
if (s->next == NULL)
{
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
}
else
{
int* ar;
int arn;
int index;
arn = num(s);
ar = arr(s, x, y);
for (int i = 0; i < arn; i++)
{
if (y == ar[i])//等于
{
index = 0;
s = s->next;
while (index < i)
{
s = s->next;
index++;
}
s->coe = s->coe + x;
break;
}
else if(y < ar[i])//小于
{
index = 0;
s= s->next;
while (index < i)
{
s= s->next;
index++;
}
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
break;
}
else//大于
{
value->next = s->next;
s->next = value;
value->coe = x;
value->exp = y;
break;
}
}
}
}
void print(ptr s)
{
s = s->next;
printf("%d^%d ", s->coe, s->exp);
while (s != NULL)
{
printf("+");
printf(" %dX^%d", s->coe, s->exp);
s = s->next;
}
}
2024年02月10日 05点02分
