devseekinghelp
devseekinghelp

Reputation: 1

Is there way to reverse the last half of the elements from the bottom of the stack (using recursion)?

The code which helps reverse the entire stack is however not able to get it to reverse half the elements -

static void reverseSecondHalf(Stack<Integer> stack) {
    // Write your code here
    
    if(stack.size() > 0)
    {
    
        int x = stack.peek();
        stack.pop();

        reverseSecondHalf(stack);
        insert_at_bottom(x,stack);}
    System.out.print(stack);
}
static void insert_at_bottom(int x, Stack<Integer> stack) {

    if(stack.isEmpty()) {
        stack.push(x);
    }
    else {
        int y = stack.peek();
        stack.pop();
        insert_at_bottom(x,stack);
        stack.push(y);
    }

}

Upvotes: 0

Views: 767

Answers (3)

samix98
samix98

Reputation: 11

You can try this in Java-

    static void reverseSecondHalf(Stack<Integer> stack, int n) {
        // Write your code here
        if (stack.size()>(n/2+1) ){
            int top= stack.pop();
            reverseSecondHalf(stack,n);
            stack.add(n/2+1,top);
        }


    }

call in main like:

reverseSecondHalf(stack, stack.size());

Upvotes: 1

vinay teja
vinay teja

Reputation: 1

static void reverseSecondHalf(Stack<Integer> stack) {
    Stack<Integer> temp = new Stack<>();
    Stack<Integer> result = new Stack<>();
    int size = stack.size();
    for (int i = 0; i < size; i++) {
        if (i < size / 2)
            temp.push(stack.pop());
        else
            result.push(stack.get(size-(i+1)));
    }
    while (!temp.isEmpty())
        result.push(temp.pop());
    for(int i=0; i<size/2;i++) {
        stack.push(result.pop());
    }
    System.out.println(stack);
}

Upvotes: -1

Kaplan
Kaplan

Reputation: 3718

this should be the shortest recursive solution

public static void reverseLastHalf(int half, Stack<Integer> stack) {
  int tos = stack.pop();
  if(stack.size() > 0)
    reverseLastHalf(half, stack);
  if(stack.size() < half)
    insert_at_bottom(tos, stack);
  else
    stack.add(tos);
}

call it like this

reverseLastHalf(stack.size() / 2, stack);

(Typically, stack-oriented languages like 7th have a function of rolling an element up from the bottom of the stack. The opposite way is unusual.)

Upvotes: 1

Related Questions