1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | #include <stdio.h> #include <stdlib.h> typedef int element; typedef struct { element* data; // dataÀº Æ÷ÀÎÅÍ·Î Á¤ÀǵȴÙ. int capacity; // ÇöÀç Å©±â int top; } StackType; // ½ºÅà »ý¼º ÇÔ¼ö void init_stack(StackType* s) { s->top = -1; s->capacity = 1; s->data = (element*)malloc(s->capacity * sizeof(element)); } // °ø¹é »óÅ °ËÃâ ÇÔ¼ö int is_empty(StackType* s) { return (s->top == -1); } // Æ÷È »óÅ °ËÃâ ÇÔ¼ö int is_full(StackType* s) { return (s->top == (s->capacity - 1)); } void push(StackType* s, element item) { if (is_full(s)) { s->capacity *= 2; s->data = (element*)realloc(s->data, s->capacity * sizeof(element)); } s->data[++(s->top)] = item; } // »èÁ¦ÇÔ¼ö element pop(StackType* s) { if (is_empty(s)) { fprintf(stderr, "½ºÅà °ø¹é ¿¡·¯\n"); exit(1); } else return s->data[(s->top)--]; } int factorial(StackType* s, int n) { int result = 1; for (int i = n; i > 0; i--) push(s, i); for (int i = n; i > 0; i--) { result *= pop(s); } return result; } int main(void) { element e; StackType s; init_stack(&s); printf("factorial(4) = %d \n", factorial(&s, 4)); printf("factorial(10) = %d \n", factorial(&s, 10)); free(s.data); return 0; } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef int element; typedef struct { element* data; // dataÀº Æ÷ÀÎÅÍ·Î Á¤ÀǵȴÙ. int capacity; // ÇöÀç Å©±â int top; } StackType; // ½ºÅà »ý¼º ÇÔ¼ö void init_stack(StackType* s) { s->top = -1; s->capacity = 1; s->data = (element*)malloc(s->capacity * sizeof(element)); } // °ø¹é »óÅ °ËÃâ ÇÔ¼ö int is_empty(StackType* s) { return (s->top == -1); } // Æ÷È »óÅ °ËÃâ ÇÔ¼ö int is_full(StackType* s) { return (s->top == (s->capacity - 1)); } void push(StackType* s, element item) { if (is_full(s)) { s->capacity *= 2; s->data = (element*)realloc(s->data, s->capacity * sizeof(element)); } s->data[++(s->top)] = item; } // »èÁ¦ÇÔ¼ö element pop(StackType* s) { if (is_empty(s)) { fprintf(stderr, "½ºÅà °ø¹é ¿¡·¯\n"); exit(1); } else return s->data[(s->top)--]; } int factorial(StackType* s, int n) { int result = 1; for (int i = n; i > 0; i--) push(s, i); for (int i = n; i > 0; i--) { result *= pop(s); } return result; } int main(void) { element e; StackType s; int num; init_stack(&s); printf("½ÊÁø¼ö: "); scanf("%d", &num); while (num > 0) { push(&s, num % 2); num /= 2; } printf("ÀÌÁø¼ö: "); while (!is_empty(&s)) { printf("%d", pop(&s)); } free(s.data); return 0; } | cs |