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

typedef struct node{
 int coefficient; //계수
 int exponent; //지수
 struct node *link; //포인터주소


}Polynomial;  //다항식의 구조체

void PolNew(Polynomial **Pol, int coef, int expo); //다항식 항추가
void PolAdd(Polynomial **D,Polynomial **Pol1, Polynomial **Pol2);
int sum(int num1, int num2);

int main()

 Polynomial *A = NULL, *B = NULL, *D = NULL;
 int NewCoef, NewExpo;
 printf("다항식 A를 생성하시오!\n");
 while(1)
 {
  printf("계수, 변수 값을 입력하시오!(End(0,0)");
  scanf("%d %d", &NewCoef, &NewExpo);
  if(NewCoef == 0 && NewExpo == 0)
   break;
  PolNew(&A, NewCoef, NewExpo);
 }
 
 printf("다항식 B를 생성하시오!\n");
 while(1)
 {
  printf("계수, 변수 값을 입력하시오!(End(0,0)");
  scanf("%d %d", &NewCoef, &NewExpo);
  if(NewCoef == 0 && NewExpo == 0)
   break;
  PolNew(&B, NewCoef, NewExpo);
 }
 
 printf("다항식 A와 다항식 B를 더한 다항식 D\n");
 PolAdd(&D, &A, &B);
 
 while(D)
 { 

  if(D->exponent == 0)
   printf("%d", D->coefficient);
  else if(D->coefficient != 0)
  {
  printf("%dX^%d ", D->coefficient, D->exponent);
  if(D->link && (D->link->coefficient) > 0)
   printf("+");
  }
  D = D->link;
 }
 printf("\n");
 return 0;
}


void PolNew(Polynomial **Pol, int coef, int expo) //다항식 항추가
{
 Polynomial *temp = (Polynomial *)malloc(sizeof(Polynomial)), *p; //새로운 노드와, 조회를 위한 포인터변수
 temp->coefficient = coef;   //계수값 집어넣기
 temp->exponent = expo; //지수값 집어넣기
 temp->link = NULL;

 if(*Pol == NULL)      //첫번째항인경우
 {
  *Pol = temp;
  return;
 }
 else    //두번째 항 이상인 경우
 {
  p = *Pol;
  while(p->link)
  {
   p = p->link;
  }
  p->link = temp;
 }
}


void PolAdd(Polynomial **D,Polynomial **Pol1, Polynomial **Pol2)

 Polynomial  *current;
 while( *Pol1 && *Pol2)
 {
  Polynomial *temp = (Polynomial *)malloc(sizeof(Polynomial));
  temp->link = NULL;
  
  if((*Pol1)->exponent < (*Pol2)->exponent)
  {
   temp->coefficient = (*Pol2)->coefficient;
   temp->exponent = (*Pol2)->exponent;
   *Pol2 = (*Pol2)->link;
   if(*D == NULL)
    *D = temp;
   else
    current->link = temp;
   
   current = temp;

  }
  else if((*Pol1)->exponent == (*Pol2)->exponent)
  {
   temp->coefficient = sum((*Pol1)->coefficient, (*Pol2)->coefficient);
   temp->exponent = (*Pol1)->exponent;
   *Pol1 = (*Pol1)->link;
   *Pol2 = (*Pol2)->link;
   if(*D == NULL)
    *D = temp;
   else
    current->link = temp;
   
   current = temp;    
  }
  else
  {
   temp->coefficient = (*Pol1)->coefficient;
   temp->exponent = (*Pol1)->exponent;
   (*Pol1) = (*Pol1)->link;
   if(*D == NULL)
    *D = temp;

   else
    current->link = temp;
   
   current = temp;
  }
 }

 if(*Pol1)
  current->link = *Pol1;
 else if(*Pol2)
  current->link = *Pol2;
 
 
}


int sum(int num1, int num2)
{
 return num1 + num2;
}



이게 저번학기 자료구조시간에 구현한 다항식 두개를 만들고 합하는 걸 연결리스트로 구현하는 과제였는데


근데 저 함수 선언부에보면 **Pol 이런식으로 이중포인터로 선언했는데 저거 왜저렇게 하는지 이유가??


저거 수업시간에 할 때 이해안되서 냅두고 어떻게 하는지만 그냥 외워서 짠건데 뭐라뭐라 설명은 했는데 잘 기억이안난다