Created
March 30, 2025 06:50
-
-
Save in1yan/e130b4d84a7c1975d68e057a0eb59d28 to your computer and use it in GitHub Desktop.
merge lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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; | |
} | |
} | |
} | |
} | |
void print_polynomial(node *head){ | |
if(head == NULL){ | |
printf("0\n"); | |
return; | |
} | |
while(head != NULL){ | |
printf("%dx^%d", head->coeff, head->exp); | |
if(head -> next != NULL) | |
printf(" + "); | |
head=head->next; | |
} | |
printf("\n"); | |
} | |
int main(){ | |
node *p=NULL; | |
int n; | |
scanf("%d", &n); | |
for(int i=0; i<n; i++){ | |
int exp, coeff; | |
scanf(" %d %d", &coeff, &exp); | |
append(&p, coeff, exp); | |
} | |
print_polynomial(p); | |
combine(&p); | |
print_polynomial(p); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment