C language implements the addition of polynomials

  • 2020-06-19 11:15:05
  • OfStack

Examples of C language polynomials to share the specific code for your reference, the specific content is as follows

Initialization of the linked list containing the lead node, output:


#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

typedef struct Pol
{
 int coe; //  The coefficient of  
 int index; //  index  
 struct Pol *next;
}Pol;

 
int main(int argc, char *argv[])
{

 Pol *head1 = NULL; //  The first 1 A polynomial 
 Pol *head2 = NULL; //  The first 2 A polynomial 
 Pol *Initiate(Pol *head1); //  Declare the initialization function 
 void Output(Pol *head);  //  Declare output function 
 void PolAdd(Pol *head1, Pol *head2); //  Declare the addition function 

 int coe, index; 
 char sign;
 Pol *p;
 int n = 0;

 //  Initialize the first 1 A polynomial 
 head1 = Initiate(head1);
 p = head1;
 while (1)
 {
 scanf("%dx%d%c", &coe, &index, &sign);

 p->next = (Pol *)malloc(sizeof(Pol));
 p = p->next;
 p->coe = coe;
 p->index = index;
 p->next = NULL;

 if(sign == '\n')
  break;
 }
 printf(" The first 1 The polynomial is finished. \n");

 //  Initialize the first 2 A polynomial 
 head2 = Initiate(head2);
 p = head2;
 while (1)
 {
 scanf("%dx%d%c", &coe, &index, &sign);

 p->next = (Pol *)malloc(sizeof(Pol));
 p = p->next;
 p->coe = coe;
 p->index = index;
 p->next = NULL;

 if (sign == '\n')
  break;
 }
 printf(" The first 2 The polynomial is finished. \n");

 //  Call the add function and the output function 
 PolAdd(head1, head2);
 Output(head1);


 system("PAUSE");
 return 0;
}

//  Initializes the list function 
Pol *Initiate(Pol *head)
{
 head = (Pol *)malloc(sizeof(Pol));
 head->next = NULL;

 return head;
}

//  Initializes the addition function 
void PolAdd(Pol *head1, Pol *head2)
{
 Pol *p = head1->next;
 Pol *q = head2->next;
 Pol *pre = head1;
 Pol *temp = NULL;
 int sum;

 while ((p != NULL) && (q != NULL))
 {
 if (p->index < q->index)
 {
  pre->next = p;
  pre = pre->next;
  p = p->next;
 }
 else if(p->index == q->index)
 {
  sum = p->coe + q->coe;
  if (sum != 0)
  {
  p->coe = sum;
  pre->next = p;
  pre = pre->next;
  p = p->next;

  //  Remove nodes 
  temp = q;
  q = q->next;
  free(temp);
  }
  else
  {
  temp = p;
  p = p->next;
  free(temp);

  temp = q;
  q = q->next;
  free(temp);
  }
 }
 else
 {
  pre->next = q;
  pre = pre->next;
  q = q->next;
 }
 }

 //  When two strings are of unequal length, put the tail 1 Time to join 
 if (p != NULL)
 pre->next = p;
 else
 pre->next = q;
 
}

//  Output function 
void Output(Pol *head)
{
 Pol *p = head;
 p = p->next;
 int i = 0;
 while (p)
 {
 if (p->coe > 0 && i != 0)
 {
  printf("+%dX^%d", p->coe, p->index);
  p = p->next;
 }
 else
 {
  printf("%dX^%d", p->coe, p->index);
  p = p->next;
 }
 i++;
 }
}

Related articles: