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\$

closed as unclear what you're asking by chux, holroy, Austin Hastings, Toby Speight, Graipher Feb 11 at 15:13

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    \$\begingroup\$ ken, What do you expect value = stack[size - 1]; to do when size == 0? \$\endgroup\$ – chux Feb 9 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.

\$\endgroup\$

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