📜  门| GATE-CS-2004 |问题5(1)

📅  最后修改于: 2023-12-03 14:58:26.398000             🧑  作者: Mango

GATE-CS-2004 Problem 5

This question tests your understanding of the Stack data structure and the use of recursion.

Problem statement

Given a stack, implement a recursive function reverse that reverses the order of elements in the stack. You are not allowed to use any additional data structure. The only functions allowed to be used are push(), pop(), and isEmpty().

public void reverse(Stack s) {
    // ???
}
Solution

To reverse a stack using recursion, we can first remove the top element from the stack and recursively reverse the remaining stack. Then, we can insert the top element at the bottom of the reversed stack.

Here is the code to implement this logic:

public void reverse(Stack s) {
    if (!s.isEmpty()) {
        int x = (int) s.pop();
        reverse(s);
        insertAtBottom(s, x);
    }
}

private void insertAtBottom(Stack s, int x) {
    if (s.isEmpty()) {
        s.push(x);
    } else {
        int y = (int) s.pop();
        insertAtBottom(s, x);
        s.push(y);
    }
}

The reverse function is a recursive function that pops the top element from the stack and recursively calls itself with the remaining stack. Then, it calls the insertAtBottom function to insert the popped element at the bottom of the reversed stack.

The insertAtBottom function is also a recursive function that pops the top element from the stack and recursively calls itself with the remaining stack. Then, it pushes the original element at the bottom of the stack.

Both functions together form a complete solution to the problem.

Conclusion

In this question, we saw how recursion can be used to reverse a given stack. We learned the importance of the Stack data structure, and the functions that can be used with it.