有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

递归跟踪java中的递归调用?

递归调用如何处理堆栈?我有一个示例代码,其中第B行printsB 654321c行printsCd行printsD 2468e行抛出一个异常。我不明白程序为什么要打印这些输出!例如,在B行中,s不是因为堆栈而变成0吗?谢谢!

public class Problem1 { 
public static void main(String args[]) { 
    Stack<Integer> s = setStack(5); printStack("A",      s); // line A 
    s = setStack(6); stackStack(s); printStack("B", s); // line B 
    s = setStack(8); cutStack(s); printStack("C", s); // line C 
    s = setStack(8); s = cutStack(s); printStack("D", s); // line D 
    s = setStack(7); s = cutStack(s); printStack("E", s); // line E 
} 
public static Stack<Integer> setStack(int n) {     
  Stack<Integer> ans = new Stack<>(); 
    for (int i = 1; i <= n; i++) 
        ans.push(i); 
    return ans; 
    }
public static void printStack(String tag, Stack<Integer> s) { 
  System.out.print(tag + " "); 
  while (!s.empty()) System.out.print(s.pop());    
  System.out.println(); 
 } 
public static Stack<Integer> cutStack(Stack<Integer> s)  
  { 
  Stack<Integer> ans = new Stack<>(); 
  while (!s.empty()) { 
     ans.push(s.pop()); 
     s.pop();
  } 
  s = ans; return s;
} 
public static void stackStack(Stack<Integer> s) { 
   if (s.empty()) return; 
   int x = s.pop(); 
   stackStack(s); 
   s.push(x); 
}
}

共 (1) 个答案

  1. # 1 楼答案

    堆栈,考虑一个较小的堆栈:123(在堆栈顶部有3个)。 设F1为stackStack()的第一个调用,F2为嵌套调用,依此类推

    F1:stackStack(123)弹出3并将其存储在x中。所以x_1=3s=12

    F2:stackStack(12)现在被调用。所以x_2=2s=1

    F3:现在stackStack(1)被调用。现在,x_3=1s是空的

    现在,s是空的。因此,控件只返回F3

    F3然后将x_3 =1推到空的s上。所以s=1控件返回到F2

    F2将x_2=2推到s=1上。所以s=12控制返回F1

    F1将x_1=3推到s=12上。所以s=123

    您刚刚得到了原始堆栈,printStack()只需打印出321

    这会让你大致了解递归的工作原理