0
\$\begingroup\$

These two functions act on a stack, an array of integers (whose first element is the top of the stack, LIFO).

The first function retrieves the first element and puts it at the end. The other is the opposite.

I would like to combine these two functions into only one function, if possible. (I have a constraint, 25 lines maximum)

int     *reverse(int value, int size, int *stack)
{
    int     value;
    int     i;
    int     *previous;

    value = *stack;
    previous = stack;
    if (!(stack = (int*)malloc(sizeof(int) * size)))
        return (NULL);
    i = 1;
    while (i < size)
    {
        stack[i - 1] = previous[i];
        i++;
    }
    stack[i - 1] = value;
    free(previous);
    return (stack);
}

int     *sv_reverse(int value, int size, int *stack)
{
    int     value;
    int     i;
    int     *previous;

    value = stack[size - 1];
    previous = stack;
    if (!(stack = (int*)malloc(sizeof(int) * size)))
        return (NULL);
    *stack = value;
    i = 1;
    while (i < size)
    {
        stack[i] = previous[i + 1];
        i++;
    }
    free(previous);
    return (stack);
}
\$\endgroup\$
  • 1
    \$\begingroup\$ ken, What do you expect value = stack[size - 1]; to do when size == 0? \$\endgroup\$ – chux - Reinstate Monica Feb 9 '19 at 16:26
1
\$\begingroup\$

I would consider an approach were you think of the array as a circular buffer, with the top of the stack being position 0. Each of your operations becomes a rotation. One position clockwise and one anticlockwise. Or even both clockwise (or anticlockwise), one a single position rotation and one a size-1 rotations.

If you can change the data structure so that the top of the stack can be any position in the circular buffer the these rotations become trivial, just set the top of value.

|improve this answer|||||
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.