Skip to content

Instantly share code, notes, and snippets.

@in1yan
Created March 30, 2025 16:33
Show Gist options
  • Save in1yan/12b8efc01779cc915ae10fd6f1614d64 to your computer and use it in GitHub Desktop.
Save in1yan/12b8efc01779cc915ae10fd6f1614d64 to your computer and use it in GitHub Desktop.
delete by exponent
# include <stdio.h>
# include <stdlib.h>
typedef struct Node{
int coeff;
int exp;
struct Node *next;
} node;
void append(node **head, int coeff, int exp){
node *new_node = (node *)malloc(sizeof(node));
new_node->coeff = coeff;
new_node->exp = exp;
new_node->next = NULL;
if(*head==NULL){
*head=new_node;
return;
}
node *tmp=*head;
while(tmp->next != NULL)
tmp = tmp->next;
tmp->next=new_node;
}
void combine(node **p){
for (node *i=*p;i != NULL; i=i->next){
for(node *j=i; j->next != NULL; ){
if(i->exp == j->next->exp){
i->coeff += j->next->coeff;
node *dup = j->next;
j->next = j->next->next;
free(dup);
}
else{
j=j->next;
}
}
}
}
node* multiply(node *p1, node *p2){
node *res = NULL;
for(node *i=p1; i != NULL; i=i->next){
for(node *j=p2; j != NULL; j=j->next){
append(&res, i->coeff * j->coeff, i->exp + j->exp);
}
}
combine( &res );
return res;
}
void print_polynomial(node *head){
while(head != NULL){
printf("%dx^%d", head->coeff, head->exp);
if(head -> next != NULL)
printf(" + ");
head=head->next;
}
printf("\n");
}
void delete_by_exponent(node **head, int exp){
node *tmp=*head, *prev = NULL;
if(tmp != NULL && tmp->exp == exp){
*head=tmp->next;
free(tmp);
return;
}
while(tmp != NULL && tmp->exp != exp){
prev = tmp;
tmp = tmp->next;
}
if(tmp == NULL) return;
prev->next = tmp->next;
free(tmp);
}
int main(){
node *p1=NULL, *p2=NULL;
int n;
scanf("%d", &n);
for(int i=0; i<n; i++){
int exp, coeff;
scanf(" %d %d", &coeff, &exp);
append(&p1, coeff, exp);
}
int m;
scanf("%d", &m);
for(int i=0; i<m; i++){
int exp, coeff;
scanf(" %d %d", &coeff, &exp);
append(&p2, coeff, exp);
}
node *res = multiply(p1, p2);
printf("Result of multiplication ");
print_polynomial(res);
int exp;
scanf("%d", &exp);
delete_by_exponent(&res ,exp);
printf("Result after deleting ");
print_polynomial(res);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment