Write a C function that inserts an element in a stack at position k (the top element is considered at position 1).


Difficulty level
Video recording
This exercise is mostly suitable for students
int insert(stack *s, element ins, int pos)
{
    int count;
    stack aux;
    element e;
    
    count=1;
    aux=CreateStack();
    while(Top(*s,&e) && count < pos)
    {
        count++;
        Pop(s);
        Push(&aux,e);
    }
    if(Push(s,ins))
    {
        while(Top(aux,&e))
        {
            Pop(&aux);
            if(!Push(s,e))
                return 0;
        }
    }
    else
        return 0;
    return 1;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Conversion of a decimal number to a number in a base between 2 and 9