동적할당을 이용한 다항식 계산 코드 좀 살펴주시면..

shs0917의 이미지

이곳에 물어도 보고 손으로 메모리도 그려보면서 우여곡절 끝에 일단 컴파일 해서 돌렸는데.. 결과값이 예상대로 나오지 않네요. 다른 방법으로 만들려면 얼마든지 할텐데.. 제대로 된 자료구조를 사용하려니 너무 어렵네요.. 제가 아직 너무 초보라서...

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

#define IS_FULL(temp) (!(temp)) 
#define Compare(x,y) (((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1)

typedef struct poly_node *poly_pointer; 
struct poly_node{ 
	int coef; 
	int exp; 
	poly_pointer link; 
}; 

void attach(int coef, int exp, poly_pointer *ptr); 
poly_pointer padd(poly_pointer a, poly_pointer b);
void eraser(poly_pointer *ptr);

void main(void){ 
	struct poly_node header1, header2;
	poly_pointer a = &header1, b = &header2, result = NULL; 
    int coef, exp; 
    printf("Input poly1(if coef is '0' then end): "); 
    while(1){ 
       printf("coef: ");      scanf("%d", &coef); 
	   if(coef == 0)
		   break;
       printf("exp: ");      scanf("%d", &exp); 
	   if(exp == 0){
		   attach(coef, exp, &a); 
		   break;
	   }
	   attach(coef, exp, &a); 
    } 

    printf("Input poly2(if coef is '0' then end): "); 
    while(1){ 
       printf("coef: ");      scanf("%d", &coef); 
	   if(coef == 0)
		   break;
       printf("exp: ");      scanf("%d", &exp); 
	   if(exp == 0){
		   attach(coef, exp, &a); 
		   break;
	   }
	   attach(coef, exp, &b); 
    } 
    
    printf("\n"); 
	
	result = padd(a, b);

	
	while(result){
		if(!(result->link))
			printf("%dx^%d\n", result->coef, result->exp);
		else
			printf("%dx^%d + ", result->coef, result->exp);
		result = result->link;
	}
	
	eraser(&a);

    exit(0); 
} 

void attach(int coef, int exp, poly_pointer *ptr){ 
	poly_pointer temp; 
	temp = (poly_pointer)malloc(sizeof(struct poly_node)); 
	if(IS_FULL(temp)){ 
		fprintf(stderr, "Memory is full!\n"); 
		exit(1); 
	} 
	temp->coef = coef; 
	temp->exp = exp; 
	temp->link = NULL;
	(*ptr)->link = temp; 
	(*ptr) = temp; 
} 

void eraser(poly_pointer *ptr){
	printf("Now Eraser!!\n");
	poly_pointer temp;
	while(*ptr){
		temp = *ptr;
		*ptr = (*ptr)->link;
		free(temp);
	}
}

poly_pointer padd(poly_pointer a, poly_pointer b){
	poly_pointer front, rear, temp;
	int sum;
	rear = (poly_pointer)malloc(sizeof(struct poly_node));
	if(IS_FULL(rear)){
		fprintf(stderr, "The memory is full\n");
		exit(1);
	}

	front = rear;

	while(a && b){
		switch(Compare(a->exp,b->exp)){
		case -1:
			attach(a->coef, a->exp, &rear);
			a = a->link;
			break;
		case 0:
			sum = a->coef + b->coef;
			if(sum)	attach(sum, a->exp, &rear);
			a = a->link;	b = b->link;
			break;
		case 1:
			attach(b->coef, b->exp, &rear);
			b = b->link;
			break;
		}
	}

	for(; a; a = a->link)	attach(a->coef, a->exp, &rear);
	for(; b; b = b->link)	attach(b->coef, b->exp, &rear);
	rear->link = NULL;

	temp = front; front = front->link;
	free(temp);
	
	return front;
}

소스 살펴봐 주신다면 정말 감사하겠습니다. 많은 지적 부탁 드립니다.
File attachments: 
첨부파일 크기
파일 examp.c1.13 KB
파일 link.c3.43 KB
ifyou의 이미지

제가 임의의 수정해 봤습니다. 제대로 동작하는 건지는 잘 모르겠고요..

그리고, 간단한 예제도 두개 만들어 봤습니다. 독학으로 배운지라

썩 좋은 예제들은 아니겠지만, 도움이 되었으면 합니다.

※ C로 쓴 자료구조론 책 있으면 보고 참조해 볼텐데 저한테는 없네요 :cry:

댓글 첨부 파일: 
첨부파일 크기
파일 0바이트
파일 0바이트
shs0917의 이미지

에구.. 이번에도 이렇게 답변을 달아주시다니.. 거기다가
예제까지 올려주셔서 너무 감사드립니다..

컴퓨터가 이해할수 있는 코드는 어느 바보나 다 작성할 수 있다. 좋은 프로그래머는 사람이 이해할 수 있는 코드를 짠다 - 마틴파울러

ifyou의 이미지

말로 설명할려니까 실력이 안되서 오히려 못해서 그냥 코드로 올렸습니다 ^^;

이런 문제에 정답은 없겠지만, 그래도 모범 답안을 드려야 되는데

제가 봐도 높은 점수를 주기 힘든 코드를 올려서 부끄럽습니다.

혹시라도 제가 올린 코드 중에서 이해가 되지 않는 부분이 있다면, 가능한한

자세히 답변하도록 하겠습니다.

ifyou의 이미지

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

#define IS_FULL(temp) (!(temp)) 
#define Compare(x,y) (((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1) 

typedef struct poly_node *poly_pointer; 
struct poly_node{ 
   int coef; 
   int exp; 
   poly_pointer link; 
}; 

void attach(int coef, int exp, poly_pointer *ptr); 
poly_pointer padd(poly_pointer a, poly_pointer b); 

void prt_list1(poly_pointer ptr)
{
	printf("-----------------------------------\n");
	while(ptr)
	{
		printf("c:%d  e:%d\n", ptr->coef, ptr->exp);
		ptr=ptr->link;
	}
	printf("-----------------------------------\n");
}

int main(void)
{ 

   poly_pointer front1, rear1, front2, rear2, temp, result; 
   int coef, exp; 
 
   rear1 = (poly_pointer)malloc(sizeof(struct poly_node)); 
   if(IS_FULL(rear1))
   { 
      fprintf(stderr, "The memory is full\n"); 
      exit(1); 
   } 

   front1 = rear1;


    printf("Input poly1(if coef is '0' then end): "); 
    while(1)
	{ 
      printf("coef: ");      scanf("%d", &coef); 
      if(coef == 0) 
         break; 
      printf("exp: ");      scanf("%d", &exp); 
      if(exp == 0)
	  { 
         attach(coef, exp, &rear1); 
         break; 
      } 
      attach(coef, exp, &rear1); 
    } 

	rear1->link=NULL;
   
	temp=front1; front1=front1->link; free(temp);

	prt_list1(rear1);
	prt_list1(front1);


	rear2 = (poly_pointer)malloc(sizeof(struct poly_node)); 
	if(IS_FULL(rear2))
	{ 
	  fprintf(stderr, "The memory is full\n"); 
	  exit(1); 
	} 

	front2 = rear2;
	
    printf("Input poly2(if coef is '0' then end): "); 
    while(1)
	{ 
      printf("coef: ");      scanf("%d", &coef); 
      if(coef == 0) 
         break; 
      printf("exp: ");      scanf("%d", &exp); 
      if(exp == 0)
	  { 
         attach(coef, exp, &rear2); 
         break; 
      } 
      attach(coef, exp, &rear2); 
    } 

    rear2->link=NULL;
   
	temp=front2; front2=front2->link; free(temp);

    printf("\n"); 

	prt_list1(rear2);
	prt_list1(front2);
    
   result = padd(front1, front2); 

   prt_list1(result);

   while(result)
   { 
      if(result->link) 
		  printf("%dx^%d + ", result->coef, result->exp); 
      else 
		  printf("%dx^%d\n", result->coef, result->exp); 
         
      result = result->link; 
   } 
    
   return 0;
} 

void attach(int coef, int exp, poly_pointer* ptr)
{ 
   poly_pointer temp; 

   temp = (poly_pointer)malloc(sizeof(struct poly_node)); 

   if(IS_FULL(temp))
   { 
      fprintf(stderr, "Memory is full!\n"); 
      exit(1); 
   } 

   temp->coef = coef; 
   temp->exp = exp; 

   (*ptr)->link=temp;
   *ptr=temp;
   temp->link = NULL; 
} 

poly_pointer padd(poly_pointer a, poly_pointer b)
{ 
   poly_pointer front, rear, temp; 
   int sum; 

   rear = (poly_pointer)malloc(sizeof(struct poly_node)); 
   if(IS_FULL(rear))
   { 
      fprintf(stderr, "The memory is full\n"); 
      exit(1); 
   } 

   front = rear; 

   while(a && b)
   { 
      switch(Compare(a->exp,b->exp))
	  { 
      case -1: 
         attach(a->coef, a->exp, &rear); 
         a = a->link; 
         break; 
      case 0: 
         sum = a->coef + b->coef; 
         if(sum)   attach(sum, a->exp, &rear); 
         a = a->link;   b = b->link; 
         break; 
      case 1: 
         attach(b->coef, b->exp, &rear); 
         b = b->link; 
         break; 
      } 
   } 

   for(; a; a = a->link)   attach(a->coef, a->exp, &rear); 
   for(; b; b = b->link)   attach(b->coef, b->exp, &rear); 

   rear->link=NULL;
   
   temp=front; front=front->link; free(temp);

   return front; 
} 

올려주신 코드에서 main()함수를 기준으로 수정했었는데, 다시 보니

원하는 것이 그게 아닌 것 같군요. 원하는 것이 맞으신가 모르겠네요.

erase()는 뺐습니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.