使用递归交换堆栈元素

问题描述 投票:0回答:1

我尝试使用递归交换堆栈的所有元素。这是我尝试过的代码,卡在 temp1 和 temp2 的初始化中。

这里我创建了两个堆栈并向其中添加了元素,名为“s1”和“s2”。我尝试将“s2”的元素交换为“s1”,将“s1”的元素交换为“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);

    }
    
}
java recursion data-structures stack
1个回答
0
投票

您可以预先将每个堆栈是否为空存储在变量中,以便有条件地推送元素。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.