Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct node{
- int exponent;
- int coefficient;
- struct node* next;
- };
- struct node* create(int e, int c){
- struct node *newNode = (struct node*) malloc(sizeof(struct node));
- newNode->exponent = e; newNode->coefficient = c; newNode->next = NULL;
- return newNode;
- }
- struct node* insert(struct node *head, struct node *newNode){
- if(!head || newNode->exponent > head->exponent){
- newNode->next = head;
- head = newNode;
- }
- else{
- struct node *help = head, *prev = NULL;
- while(help && newNode->exponent < help->exponent){
- prev = help;
- help = help->next;
- }
- if(help && newNode->exponent == help->exponent) help->coefficient+=newNode->coefficient;
- else{
- newNode->next = help;
- prev->next = newNode;
- }
- }
- return head;
- }
- void display(struct node* head){
- struct node *help = head;
- while(help){
- printf("%d", help->coefficient);
- printf("X^(%d)+", help->exponent);
- help = help->next;
- }
- printf("0");
- }
- struct node* enter(struct node *head, int n){
- int i, e, c;
- for(i = 0; i < n; i++){
- printf("\n\nEnter the exponent: ");
- scanf("%d", &e);
- printf("Enter the coefficient: ");
- scanf("%d", &c);
- head = insert(head, create(e,c));
- }
- return head;
- }
- struct node *copy(struct node* headC, struct node* headA){
- struct node *last = NULL;
- while(headA){
- struct node* newNode = create(headA->exponent, headA->coefficient);
- if(!headC) headC = last = newNode;
- else{
- last->next = newNode;
- last = newNode;
- }
- headA = headA->next;
- }
- return headC;
- }
- void add(struct node *headA, struct node *headB){
- struct node *headC = NULL;
- headC = copy(headC, headA);
- struct node *helpB = headB;
- while(helpB){
- headC = insert(headC, create(helpB->exponent, helpB->coefficient));
- helpB = helpB->next;
- }
- printf("\n\nThe addition of polinomials A and B is ");
- display(headC);
- }
- void sub(struct node *headA, struct node *headB){
- struct node *headC = NULL;
- headC = copy(headC, headA);
- struct node *helpB = headB;
- while(helpB){
- headC = insert(headC, create(helpB->exponent, -helpB->coefficient));
- helpB = helpB->next;
- }
- printf("\nThe subtraction of polinomials A and B is ");
- display(headC);
- }
- int main(){
- int nA, nB;
- struct node *headA = NULL;
- struct node *headB = NULL;
- printf("Enter the number of terms for A: ");
- scanf("%d", &nA);
- headA = enter(headA, nA);
- printf("\nEnter the number of terms for B: ");
- scanf("%d", &nB);
- headB = enter(headB, nB);
- printf("\n\nPolynomial A is :- ");
- display(headA);
- printf("\nPolynomial B is :- ");
- display(headB);
- add(headA, headB);
- sub(headA, headB);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement