简体   繁体   English

合并链接列表中的递归

[英]Recursion In Merging Linked Lists

I am beginning to understand recursion, 我开始理解递归,

I have attached the recursion code to merge two sorted linked lists, 我已经附上了递归代码以合并两个排序的链表,

My problem is, I understand that 'temp' returns the value of temp->(first (or) second) once the first or second becomes null, but I am unable to understand the fact that, 我的问题是,我了解到“ temp”会在第一个或第二个为空时返回temp->(第一(或)第二)的值,但是我无法理解以下事实:

Say for instance if I have 5 -> 10 -> 15 -> 20. 假设我有5-> 10-> 15-> 20。

The final function returns 15 ->20 which is then combined as root.next-> temp, but after that step when I return temp, why does the root value gets returned. 最终函数返回15-> 20,然后将其组合为root.next-> temp,但是在我返回temp的那一步之后,为什么返回根值。 ie 10 -> 15 -> 20, when I expect only temp to be returned. 即10-> 15-> 20,当我希望只返回温度时。

Please find the code, 请找到代码,

 /**
 * 
 */
 *
 *
 */
public class MergeLinkedLists {

    static class Node {

        int data;
        Node next;

        public Node(int value) {
            this.data = value;
        }

    }

    Node root;

        /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MergeLinkedLists s1 = new MergeLinkedLists();
        s1.root = new Node(0);
        Node n1 = new Node(10);
        //n1.next = new Node(20);
        //n1.next.next = new Node(30);

        Node n2 = new Node(5);
        n2.next = new Node(15);
        //n2.next.next = new Node(50);

        Node result = sortedLists(n1, n2, s1.root);

        while (result != null) {
            System.out.print(result.data + "--->");
            result = result.next;
        }
    }

    /**
     * @param n1
     * @param n2
      * @param root2
     */
     private static Node sortedLists(Node n1, Node n2, Node root) {
         // TODO Auto-generated method stub

        Node temp = root;

        Node first = n1; // 10 20 30
        Node second = n2; // 5 15 50

        if (first == null) {
            temp.next = second;
            return temp;
        } else if (second == null) {
            temp.next = first;
            return temp;
        }

        else if (first.data < second.data) {
            temp = new Node(first.data);
            first = first.next;
        } else {
            temp = new Node(second.data);
            second = second.next;
        }

        sortedLists(first, second, temp);
        root.next = temp;
        System.out.println("The Temp Data is ::::"+temp.data);
        return temp;

    }

}

Because temp is in this case the root value. 因为在这种情况下, temp 根值。 Don't worry, this is the one thing you need to understand in order to understand recursion itself. 不用担心,这是您需要了解递归本身的一件事。

A great feature to understand the functionality of your code is to use the debugger. 理解代码功能的一个重要功能就是使用调试器。 Set a breakpoint to the function call and you can step through the program, while you can observe how the variables change. 在函数调用中设置一个断点,就可以逐步执行程序,同时可以观察变量的变化。

This aside, let's have a look at your code. 除此之外,让我们看一下您的代码。

Important to note is that whenever you call your sortedLists(first, second, temp); 需要注意的重要一点是,每当您调用sortedLists(first, second, temp); the pointer will get into it until the function terminates (so when it returns temp). 指针将进入它,直到函数终止(因此当它返回temp时)。 You will call this function multiple times as the program continues, so it will get deeper into its own function. 随着程序的继续,您将多次调用此函数,因此它将更深入地了解其自身的功能。 It then carries the information step-by-step on level up until the first call of sortedLists(first, second, temp); 然后,它将逐步逐步携带信息,直到第一次调用sortedLists(first, second, temp);为止sortedLists(first, second, temp); terminates and this is in your main method Node result = sortedLists(n1, n2, s1.root); 终止,这在您的主要方法中Node result = sortedLists(n1, n2, s1.root);

I will try to get along with your example: 我将尝试与您的示例相处:

  1. Node result = sortedLists(n1, n2, s1.root); called in the main() method. main()方法中调用。 So the root is 0 and you have your nodes 10 and 5,15. 因此根为0,您的节点为10和5,15。

  2. In the first call of sortedLists() temp becomes 5 and second now carries a 15, because first.data > second.data . 在第一次调用sortedLists() temp变为5, second现在携带15,因为first.data > second.data

  3. NOW You call the method sortedLists() again but with new values: the root is now 5, first remains 10 and second is 15. We step inside the function and start with the new values: 现在,您再次调用sortedLists()方法,但使用新值:现在根是5,第一个仍然是10,第二个是15。我们进入函数并从新值开始:

    1. because of first.data < second.data , temp becomes 10, first is now null. 由于first.data < second.data ,temp变为10,first现在为null。
    2. and again: we reached another call on sortedLists() . 一次又一次:我们在sortedLists()上达到了另一个调用。 We pass the values: first = null second = 15 root = 10 to the function and go one step deeper. 我们将值传递给该函数: first = null second = 15 root = 10 ,然后再深入一步。
      1. as first is now zero, temp.next will be second (15) 因为first现在是零, temp.next将是second (15)
      2. temp looks like this now: 10->15 and we return. temp现在看起来像这样:10-> 15,我们返回。 (this is the first time, sortedLists() terminates!) (这是第一次sortedLists()终止!)
    3. We are now back here and can move on with root.next = temp; 我们现在回到这里,可以继续使用root.next = temp; Remember what temp was in this context? 还记得这种情况下的温度吗? temp was 10 but it has been updated by the function above. temp是10,但已通过上述功能进行了更新。 The new temp is 10->15, so our root looks like: 5->10->15. 新的temp是10-> 15,所以我们的root看起来像是:5-> 10-> 15。
    4. Then you print the head of temp, which is 10. This function also terminates. 然后打印temp的开头,即10。此功能也会终止。
  4. now we are back in our first call and see what happens: in 3.3 we updated the root of it. 现在我们回到第一个调用中,看看会发生什么:在3.3中,我们更新了它的根。 The root of 3.3 was the temp of 3 because we called sortedLists(first, second, temp) (temp acts as the root because the last argument of this function is Node root ). 3.3的根是3的温度,因为我们调用了sortedLists(first, second, temp) (temp用作根,因为此函数的最后一个参数是Node root )。

  5. To sum up: Our root is still 0 and our temp is 5->10->15 总结:我们的根仍然是0,温度是5-> 10-> 15

  6. root.next is after this assignment 0->5->10->15. root.next在此分配后为0-> 5-> 10-> 15。 Now the root you declared in your class above the main method has a value. 现在,您在类中的main方法上方声明的根具有值。

  7. we return the temp which is 5->10->15 and we are done. 我们返回的温度是5-> 10-> 15,我们完成了。

We now can proceed in the main method, printing the results. 现在,我们可以继续main方法,打印结果。

To get rid of the ---> when there is no result.next , you can handle the null value like this: 要在没有result.next时摆脱--->,可以像这样处理null值:

 while (result != null) {
            if (result.next != null)
            System.out.print(result.data + "--->");
            else System.out.println(result.data);
            result = result.next;
        }

I hope this helps a bit to get into recursion. 我希望这有助于递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM