Search code examples
javarecursiondata-structuresstack

Swap elements of stack using recursion


I tried swapping all the elements of stack using recursion. Here is the code which I have tried, got stuck in initialisation of temp1 and temp2.

Here I have created two stacks and added elements to it, named 's1' and 's2'. I have tried swapping elements of 's2' into 's1' and elements of 's1' to 's2'.

import java.util.Stack;

//Exchange the elements of stack i.e s1 will contain elements of s2 and s2 will contain elements of s1.
public class RecursionExchangeElementsStack {

    void exchangeStack(Stack<Integer> s1, Stack<Integer> s2){
        //int temp1=s1.peek();
        //int temp2=s2.peek();

        if(s1.empty() && s2.empty()){
            return;
        }
        
        if(!s1.empty()){
        int temp1 = s1.peek();
        s1.pop();
        }
        if(!s2.empty()){
        int temp2 = s2.peek();
        s2.pop();
        }

        exchangeStack(s1, s2);
        s1.push(temp2);
        s2.push(temp1);
    }


    public static void main(String[] args) {
        Stack<Integer> s1 = new Stack<Integer>();
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);

        Stack<Integer> s2 = new Stack<Integer>();
        s2.push(5);
        s2.push(6);
        s2.push(7);
        //s2.push(8);

        RecursionExchangeElementsStack re = new RecursionExchangeElementsStack();
        re.exchangeStack(s1, s2);
        System.out.println(s1);
        System.out.println(s2);

    }
    
}

Solution

  • You can store if each stack is empty in a variable beforehand in order to conditionally push elements.

    void exchangeStack(Stack<Integer> s1, Stack<Integer> s2){
        boolean s1Empty = s1.empty(), s2Empty = s2.empty();
        if (s1Empty && s2Empty) return;
        Integer temp1 = s1Empty ? null : s1.pop(), temp2 = s2Empty ? null : s2.pop();
        exchangeStack(s1, s2);
        if (!s2Empty) s1.push(temp2);
        if (!s1Empty) s2.push(temp1);
    }