Created
March 11, 2025 14:49
-
-
Save in1yan/dea2469fc1f5cba7816d942314dd913b to your computer and use it in GitHub Desktop.
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> | |
struct node { | |
int coeff; | |
int exp; | |
struct node *next; | |
}; | |
void insertEnd(struct node **head,int coeff, int exp); | |
void printList(struct node *head); | |
struct node* add(struct node *p1, struct node *p2); | |
int main(){ | |
struct node *p1 = NULL, *p2=NULL; | |
int n, m; | |
scanf("%d", &n); | |
for(int i=0; i<n; i++){ | |
int coeff, exp; | |
scanf("%d %d", &coeff, &exp); | |
insertEnd(&p1, coeff, exp); | |
} | |
scanf("%d", &m); | |
for(int i=0; i<m; i++){ | |
int coeff, exp; | |
scanf("%d %d", &coeff, &exp); | |
insertEnd(&p2, coeff, exp); | |
} | |
printList(p1); | |
printList(p2); | |
struct node *res = add(p1,p2); | |
printList(res); | |
int coeff_sum =0; | |
while(res!=NULL){ | |
coeff_sum += res->coeff; | |
res = res->next; | |
} | |
printf("sum : %d", coeff_sum); | |
} | |
void insertEnd(struct node **head, int coeff, int exp){ | |
struct node *new = (struct node *)malloc(sizeof(struct node)); | |
new->coeff = coeff; | |
new->exp = exp; | |
new->next=NULL; | |
if(*head==NULL){ | |
*head=new; | |
return; | |
} | |
struct node *tmp = *head; | |
while(tmp->next != NULL) | |
tmp = tmp->next; | |
tmp->next = new; | |
} | |
struct node* add(struct node *p1, struct node *p2){ | |
struct node *sum = NULL; | |
while(p1 != NULL && p2 !=NULL){ | |
if(p1->exp > p2->exp){ | |
insertEnd(&sum,p1->coeff, p1->exp); | |
p1=p1->next; | |
} | |
else if(p1->exp < p2->exp){ | |
insertEnd(&sum,p2->coeff, p2->exp); | |
p2=p2->next; | |
} | |
else{ | |
insertEnd(&sum, p1->coeff+p2->coeff, p1->exp); | |
p1=p1->next; | |
p2=p2->next; | |
} | |
} | |
while(p1!=NULL){ | |
insertEnd(&sum, p1->coeff, p1->exp); | |
p1=p1->next; | |
} | |
while(p2!=NULL){ | |
insertEnd(&sum, p2->coeff, p2->exp); | |
p2=p2->next; | |
} | |
return sum; | |
} | |
void printList(struct node *head){ | |
struct node *tmp = head; | |
while(tmp != NULL){ | |
printf("(%d, %d) -> ", tmp->coeff, tmp->exp); | |
tmp = tmp->next; | |
} | |
printf("NULL\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment