Sunday, August 12, 2012

Reverse a stack in place (without extra memory)



// You are given access to functions push, pop and isempty
void reverse(stack s){
        if(!isempty(s)){
                int temp = pop(s);
                reverse(s);
                pushtobottom(s,temp);
        }
}
 
pushtobottom(stack s, int data){
        if(!isempty(s)){
                temp = pop(s);
                pushtobottom(s,data);
                push(s,temp);
        } else {
                push(s,data);
        }
}

1 comment:

  1. this solution uses system stack which is a memory. So "without extra memory" is not correct statement.

    ReplyDelete