Advertisement
Guest User

Untitled

a guest
Dec 7th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. #include <limits.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int ilosc_krokow = 0;
  5.  
  6. struct Dictionary
  7. {
  8. int key;
  9. int value;
  10. };
  11. struct Stack
  12. {
  13. int top;
  14. unsigned capacity;
  15. struct Dictionary *array;
  16. };
  17.  
  18. // function to create a stack of given capacity. It initializes size of
  19. // stack as 0
  20. struct Stack *createStack(unsigned capacity)
  21. {
  22. struct Stack *stack = (struct Stack *)malloc(sizeof(struct Stack));
  23. stack->capacity = capacity;
  24. stack->top = -1;
  25. stack->array = (struct Dictionary *)malloc(stack->capacity * sizeof(struct Dictionary));
  26. return stack;
  27. }
  28.  
  29. // Stack is full when top is equal to the last index
  30. int isFull(struct Stack *stack)
  31. {
  32. return stack->top == stack->capacity - 1;
  33. }
  34.  
  35. // Stack is empty when top is equal to -1
  36. int isEmpty(struct Stack *stack)
  37. {
  38. return stack->top == -1;
  39. }
  40.  
  41. // Function to add an item to stack. It increases top by 1
  42. void push(struct Stack *stack, struct Dictionary item)
  43. {
  44. if (isFull(stack))
  45. return;
  46. stack->array[++stack->top] = item;
  47. }
  48.  
  49. // Function to remove an item from stack. It decreases top by 1
  50. struct Dictionary pop(struct Stack *stack)
  51. {
  52. if (isEmpty(stack))
  53. {
  54. struct Dictionary ret;
  55. ret.key = 0;
  56. ret.value = 0;
  57. return ret;
  58. }
  59. return stack->array[stack->top--];
  60. }
  61.  
  62. // Function to return the top from stack without removing it
  63. struct Dictionary peek(struct Stack *stack)
  64. {
  65. if (isEmpty(stack)){
  66. struct Dictionary ret;
  67. ret.key = 0;
  68. ret.value = 0;
  69. return ret;
  70. }
  71.  
  72. return stack->array[stack->top];
  73. }
  74. struct Stack *stack;
  75. int fibo(int n)
  76. {
  77. struct Dictionary end;
  78. ilosc_krokow++;
  79. if (n == 0)
  80. {
  81. end.key = n;
  82. end.value = 0;
  83. push(stack, end);
  84. return 0;
  85. }
  86. else if (n == 1 || n == 2)
  87. {
  88. end.key = n;
  89. end.value = 1;
  90. push(stack, end);
  91. return 1;
  92. }
  93. int wynik = fibo(n - 2) + fibo(n - 1);
  94. end.key = n;
  95. end.value = wynik;
  96. push(stack, end);
  97. return wynik;
  98. }
  99. int main()
  100. {
  101. stack = createStack(100);
  102. fibo(5);
  103. int i;
  104. for (i = 1; i <= ilosc_krokow; i++)
  105. {
  106. struct Dictionary print = pop(stack);
  107. printf("fibo%d(%d) = %d \n", i, print.key, print.value);
  108. }
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement