Создать два стека на одном массиве - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Задание такое: при реализации стека массивом располагать два стека в одном массиве. Один стек располагается в начале массива и растет к концу, а другой располагается в конце массива и растет к началу. Задание я понял не очень, но что-то попытался реализовать, можете объяснить мне задпние подробнее.Вот, до чего додумался
Листинг программы
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAX_SIZE 1
  4. #define MULT 1
  5. #define STACK_OVERFLOW -100
  6. #define STACK_UNDERFLOW -101
  7. #define OUT_OF_MEMORY -102
  8. typedef struct Stack_tag
  9. {
  10. int *data;
  11. int size;
  12. int top;
  13. }stack_t, stack_d;
  14. //------------------------------stack_1-----------------------------
  15. stack_t *creat_stack()
  16. {
  17. stack_t *out = NULL;
  18. out = malloc(sizeof(stack_t));
  19. if(!out)
  20. exit(OUT_OF_MEMORY);
  21. out->size = MAX_SIZE;
  22. out->data = malloc(out->size*sizeof(int));
  23. if (out->data==NULL)
  24. {
  25. free(out);
  26. exit(OUT_OF_MEMORY);
  27. }
  28. out->top = 0;
  29. return out;
  30. }
  31. void delete_stack(stack_t **stack)
  32. {
  33. free((*stack)->data);
  34. free(*stack);
  35. *stack = NULL;
  36. }
  37. void resize(stack_t *stack)
  38. {
  39. stack->size += MULT;
  40. stack->data = realloc(stack->data,stack->size*sizeof(int));
  41. if (stack->data == NULL)
  42. exit(OUT_OF_MEMORY);
  43. }
  44. //-----------------------------------------------------------------------------
  45. void push(stack_t *stack, int value)
  46. {
  47. if (stack->top >= stack->size)
  48. resize(stack);
  49. stack->data[stack->top]= value;
  50. stack->top++;
  51. }
  52. void push_1(stack_d *stack, int value)
  53. {
  54. if (stack->top >= stack->size)
  55. resize(stack);
  56. stack->data[stack->top]= value;
  57. stack->top--;
  58. }
  59. int pop(stack_t *stack)
  60. {
  61. if(stack->top == 0)
  62. exit(STACK_UNDERFLOW);
  63. stack->top--;
  64. return (stack->data[stack->top]);
  65. }
  66. void print_stack_value(const int value)
  67. {
  68. printf("%d", value);
  69. }
  70. void print_stack(const stack_t *stack, void(*print_stack_value)(const int))
  71. {
  72. int len=stack->size-1;
  73. int i;
  74. for(i = len; i > 0; i--)
  75. {
  76. print_stack_value(stack->data[i]);
  77. printf(" | ");
  78. }
  79. if (stack->size != 0)
  80. {
  81. print_stack_value(stack->data[i]);
  82. }
  83. printf("\n");
  84. }
  85. int main()
  86. {
  87. stack_t *stack_1 = creat_stack();
  88. stack_t *stack_2 = creat_stack();
  89. int a;
  90. printf("Input quantyty items: ");
  91. scanf("%d",&a);
  92. push(stack_1, a);
  93. print_stack(stack_1, print_stack_value);
  94. printf("Input quantyty items: ");
  95. scanf("%d",&a);
  96. push_1(stack_2, a);
  97. print_stack(stack_2, print_stack_value);
  98. return 0;
  99. }
Вот, переделал, теперь что-то похожее. 2 стека в одном массиве, один растет от начала массива к концу, а другой от конца к началу, только вот когда кладу элементы в первый стек, вроде все нормально. а когда во второй, то ничего не работает, почему?
Листинг программы
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define MAX_SIZE 10
  4. #define MULT 1
  5. #define STACK_OVERFLOW -100
  6. #define STACK_UNDERFLOW -101
  7. #define OUT_OF_MEMORY -102
  8. typedef struct Stack_tag
  9. {
  10. int data[MAX_SIZE];
  11. int size;
  12. int top1, top2;
  13. }stack_t;
  14. //------------------------------stack_1-----------------------------
  15. void push(stack_t *stack, int value)
  16. {
  17. stack->data[stack->top1]= value;
  18. stack->top1++;
  19. }
  20. void push_1(stack_t *stack, int value)
  21. {
  22. stack->data[stack->top2]= value;
  23. stack->top2--;
  24. }
  25. int pop(stack_t *stack)
  26. {
  27. if(stack->top1 == 0)
  28. exit(STACK_UNDERFLOW);
  29. stack->top1--;
  30. return (stack->data[stack->top1]);
  31. }
  32. void print_stack_value(const int value)
  33. {
  34. printf("%d", value);
  35. }
  36. void print_stack_1(const stack_t *stack, void(*print_stack_value)(const int))
  37. {
  38. int len_1 = stack -> top1;
  39. int i = 0;
  40. for(i = len_1-1; i >= 0; i--)
  41. {
  42. print_stack_value(stack->data[i]);
  43. printf(" | ");
  44. }
  45. }
  46. void print_stack_2(const stack_t *stack, void(*print_stack_value)(const int))
  47. {
  48. int len_2 = stack -> top2;
  49. int j;
  50. for(j = len_2; j >= 0; j--)
  51. {
  52. print_stack_value(stack->data[j]);
  53. printf(" | ");
  54. }
  55. }
  56. int main()
  57. {
  58. int a;
  59. stack_t stack_1;
  60. stack_1.top1 = 0;
  61. stack_1.top2 = MAX_SIZE;
  62. printf("Input quantyty items: ");
  63. scanf("%d",&a);
  64. push(&stack_1, a);
  65. printf("Input quantyty items: ");
  66. scanf("%d",&a);
  67. push(&stack_1, a);
  68. print_stack_1(&stack_1, print_stack_value);
  69. printf("Input quantyty items: ");
  70. scanf("%d",&a);
  71. push_1(&stack_1, a);
  72. print_stack_2(&stack_1, print_stack_value);
  73. return 0;
  74. }

Решение задачи: «Создать два стека на одном массиве»

textual
Листинг программы
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #define DEFAULT_STACK_SIZE (10)
  5.  
  6. typedef int data_t;
  7. #define DATA_MASK "%d"
  8.  
  9. typedef struct TWO_WAY_STACK {
  10.     data_t * pData;
  11.     data_t * pHead;
  12.     data_t * pTail;
  13.     size_t nSize;
  14. } twstack_t;
  15.  
  16. twstack_t * twstack_new(size_t size) {
  17.     twstack_t * stk = malloc(sizeof(twstack_t));
  18.     if ( ! stk )
  19.         return NULL;
  20.    
  21.     if ( ! ( stk->pData = malloc(sizeof(data_t) * size) ) ) {
  22.         free(stk);
  23.         return NULL;
  24.     }
  25.    
  26.     stk->nSize = size;
  27.     stk->pHead = stk->pData - 1;
  28.     stk->pTail = stk->pData + stk->nSize;
  29.    
  30.     return stk;
  31. }
  32.  
  33. int twstack_push_head(twstack_t * stk, const data_t data) {
  34.     if ( stk->pHead + 1 >= stk->pTail )
  35.         return -1;
  36.    
  37.     *(++(stk->pHead)) = data;
  38.    
  39.     return 0;
  40. }
  41.  
  42. int twstack_pop_head(twstack_t * stk, data_t * dataHolder) {
  43.     if ( stk->pHead < stk->pData )
  44.         return -1;
  45.    
  46.     *dataHolder = *(stk->pHead--);
  47.    
  48.     return 0;
  49. }
  50.  
  51. int twstack_push_tail(twstack_t * stk, const data_t data) {
  52.     if ( stk->pTail - 1 <= stk->pHead )
  53.         return -1;
  54.    
  55.     *(--(stk->pTail)) = data;
  56.    
  57.     return 0;
  58. }
  59.  
  60. int twstack_pop_tail(twstack_t * stk, data_t * dataHolder) {
  61.     if ( stk->pTail >= stk->pData + stk->nSize )
  62.         return -1;
  63.    
  64.     *dataHolder = *(stk->pTail++);
  65.    
  66.     return 0;
  67. }
  68.  
  69. void twstack_free(twstack_t * stk) {
  70.     free(stk->pData);
  71.     free(stk);
  72. }
  73.  
  74. void flush_input(void) {
  75.     char ch;
  76.    
  77.     while ( scanf("%c", &ch) == 1 && ch != '\n' )
  78.         ;
  79. }
  80.  
  81. int main(void) {
  82.     twstack_t * stk;
  83.     data_t data;
  84.     int choose;
  85.    
  86.     if ( ! ( stk = twstack_new(DEFAULT_STACK_SIZE) ) ) {
  87.         fprintf(stderr, "Memory error!\n");
  88.         return 1;
  89.     }
  90.    
  91.     while ( printf("[1 = help]> ") > 0 && scanf("%d", &choose) == 1 && choose ) {
  92.         switch ( choose ) {
  93.             case 1:
  94.                 printf("0 = exit\n"
  95.                        "1 = this help\n"
  96.                        "2 = push head\n"
  97.                        "3 = pop head\n"
  98.                        "4 = push tail\n"
  99.                        "5 = pop tail\n\n"
  100.                 );
  101.                 break;
  102.             case 2:
  103.                 printf("Data: ");
  104.                 if ( scanf(DATA_MASK, &data) != 1 ) {
  105.                     flush_input();
  106.                     printf("Wrong input!\n");
  107.                 }
  108.                 else if ( twstack_push_head(stk, data) )
  109.                     printf("Stack is full!\n");
  110.                 else
  111.                     printf("OK.\n");
  112.                 break;
  113.             case 3:
  114.                 if ( twstack_pop_head(stk, &data) )
  115.                     printf("Head part is empty!\n");
  116.                 else
  117.                     printf("Returned value: " DATA_MASK "\n", data);
  118.                 break;
  119.             case 4:
  120.                 printf("Data: ");
  121.                 if ( scanf(DATA_MASK, &data) != 1 ) {
  122.                     flush_input();
  123.                     printf("Wrong input!\n");
  124.                 }
  125.                 else if ( twstack_push_tail(stk, data) )
  126.                     printf("Stack is full!\n");
  127.                 else
  128.                     printf("OK.\n");
  129.                 break;
  130.             case 5:
  131.                 if ( twstack_pop_tail(stk, &data) )
  132.                     printf("Tail part is empty!\n");
  133.                 else
  134.                     printf("Returned value: " DATA_MASK "\n", data);
  135.                 break;
  136.             default:
  137.                 printf("Unknown selection!\n");
  138.                 break;
  139.         }
  140.     }
  141.    
  142.     twstack_free(stk);
  143.     return 0;
  144. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

8   голосов , оценка 3.5 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы