Thursday, October 24, 2013

Write a method to reverse a Stack inplace using push and pop operations only


We need two methods

one to recursively pop all stack elements. if you push them back in the same func . you willl get same stack as stack is a LIFO.

so to reverse you need another function to take the popped elements in reverse order and push them in the same order.

Below code does the same
void insertAtBtm(struct Stack *stk,int data)
{
    int temp;
    if (isEmpty(stk)) {
        push(stk,data);
        return ;
    }
    temp = pop(stk);
    insertAtBtm(stk,data);
    push(stk,temp);
}


void revStack (struct Stack *stk)
{
    int data;
    if (isEmpty(stk))
        return;
    data = pop(stk);
    revStack(stk);
    insertAtBtm(stk,data);
 }

No comments:

Post a Comment