簡體   English   中英

如何僅使用堆棧實現遞歸函數?

[英]How to implement recursive function only using stacks?

我有一個分配給我遞歸函數的任務,並且必須僅使用堆棧(無遞歸)重寫它。 我不知道如何實現以下功能

public static void fnc1(int a, int b) {
    if (a <= b) {
        int m = (a+b)/2;
        fnc1(a, m-1);
        System.out.println(m);
        fnc1(m+1, b);
    }
}

問題是我無法弄清楚如何在有頭尾遞歸的情況下實現遞歸函數。

我試圖遍歷一個堆棧,每次彈出一個值 (a, b) 並推送一個新值 (a, m-1) 或 (m+1, b) 而不是校准“fnc1()”,但輸出總是出問題。

編輯:這是我嘗試的代碼:

public static void Fnc3S(int a, int b) {
        myStack stack1_a = new myStack();
        myStack stack1_b = new myStack();

        myStack output = new myStack();

        stack1_a.push(a);
        stack1_b.push(b);

        while(!stack1_a.isEmpty()) {

            int aVal = stack1_a.pop();
            int bVal = stack1_b.pop();
            if(aVal <= bVal) {
                int m = (aVal+bVal)/2;

                stack1_a.push(aVal);
                stack1_b.push(m-1);

                output.push(m);

                stack1_a.push(m+1);
                stack1_b.push(bVal);

            }
        }
        while(!output.isEmpty()) {
            System.out.println(output.pop());
        }
    }

這輸出:

(a, b) = (0, 3)
Recursive: 
0
1
2
3
Stack Implementation: 
0
3
2
1

要正確實現此遞歸,您需要了解執行發生的順序,然后以相反的順序插入變量(作為堆棧彈出最新元素):

檢查下面的代碼和評論:

public static void Fnc3S(int a, int b) {
    Stack<Integer> stack = new Stack<>(); // single stack for both input variables
    Stack<Integer> output = new Stack<>(); // single stack for output variable

    stack.push(a); // push original input
    stack.push(b);

    do {
        int bVal = stack.pop();
        int aVal = stack.pop();

        if (aVal <= bVal) {
            int m = (aVal + bVal) / 2;
            output.push(m); // push output

            stack.push(m + 1); // start with 2nd call to original function, remember - reverse order
            stack.push(bVal);

            stack.push(aVal); // push variables used for 1st call to original function
            stack.push(m - 1);
        } else {
            if (!output.empty()) { // original function just returns here to caller, so we should print any previously calculated outcome
                System.out.println(output.pop());
            }
        }
    } while (!stack.empty());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM