Consider a language that does not have arrays but does have stacks as a data type. That is, one can declare stack s; and the operations push, pop, top operations are defined. Show how a one-dimensional array can be implemented by using these operations on two stacks.


Difficulty level
Video recording
This exercise is mostly suitable for students
typedef struct  {
	stack s; 
	int nb_elements;
} Array;

Array CreateArray(int size)
{
	Array a;
	int i;
	a.s=CreateStack();
	for(i=0;i<size;i++)
		Push(&(a.s),0);
	a.nb_elements=size;
	return a;
}

int Assign(Array *A, element n, int index)
{
	int i;
	element e;
	stack aux;
	
	if(index<0 || index>A->nb_elements)
		return 0;

    	aux=CreateStack();
	for(i=A->nb_elements-1; i>index; i--)
	{
		Top(A->s,&e);
		Pop(&(A->s));
		Push(&aux,e);
	}
	Pop(&(A->s));
	Push(&(A->s),n);
	while(Top(aux,&e))
	{
		Pop(&aux);
		Push(&(A->s),e);
	}

	return 1;
}

void printr(Array A)
{
    element e;
    if(!isEmptyStack(A.s))
    {
        Top(A.s,&e);
        Pop(&(A.s));
        printr(A);
        printf("%5d ", e);
    }
}

void print(Array A, int size)
{
 
    int i;
    for(i=1;i<=A.nb_elements - size ; i++)
        Pop(&(A.s));
    printr(A);
    printf("\n");
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Automata