Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过在每次循环中将链表一分为二,递归地反转单个链表_Java_Algorithm_Linked List - Fatal编程技术网

Java 通过在每次循环中将链表一分为二,递归地反转单个链表

Java 通过在每次循环中将链表一分为二,递归地反转单个链表,java,algorithm,linked-list,Java,Algorithm,Linked List,我如何用java编写一个函数,通过将一个单链表分成一半(第一部分是(n/2)个节点,其余部分是第二部分(n是喜欢的列表的大小)来反转它,直到它到达一个节点,然后合并这个分割的部分。允许在每个分区中使用两个新的链表,但不允许使用列表节点。函数必须为void,且函数没有参数。我有主链表的头和尾 我在网站上找到了这段代码,但它并没有将链表一分为二,所以它并没有什么帮助 static ListNode reverseR(ListNode head) { if (head == null || h

我如何用java编写一个函数,通过将一个单链表分成一半(第一部分是(n/2)个节点,其余部分是第二部分(n是喜欢的列表的大小)来反转它,直到它到达一个节点,然后合并这个分割的部分。允许在每个分区中使用两个新的链表,但不允许使用列表节点。函数必须为void,且函数没有参数。我有主链表的头和尾

我在网站上找到了这段代码,但它并没有将链表一分为二,所以它并没有什么帮助

static ListNode reverseR(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }

    ListNode first = head;
    ListNode rest = head.next;

    // reverse the rest of the list recursively
    head = reverseR(rest);

    // fix the first node after recursion
    first.next.next = first;
    first.next = null;

    return head;
}

因为您使用的是链表,所以您建议的方法不太可能有效。确定中点的位置是一个线性时间操作,即使列表的大小已知,您仍然需要迭代到中点。因为在递归树的每个节点上都有一个线性项,所以总体性能将是O(n lg n),比您提供的代码的O(n)界慢

尽管如此,您仍然可以通过以下策略来扭转列表:

 Step 1: Split the list L into A (the first half) and B (the second half).
 Step 2: Recurse on each of A and B. This recursion should bottom out 
         when given a list of length 1.
 Step 3: Attach the new head of the reversed A to the new tail of the reversed B.

你可以看到,首先,我们的列表是AB。然后我们递归得到A'和B',每一个都是半列表的反向版本。然后输出新的反向列表B'A'。原始A的第一个元素现在是列表的最后一个元素,原始B的最后一个元素现在是列表的第一个元素。

因为您使用的是链接列表,所以您建议的方法不太可能有效。确定中点的位置是一个线性时间操作,即使列表的大小已知,您仍然需要迭代到中点。因为在递归树的每个节点上都有一个线性项,所以总体性能将是O(n lg n),比您提供的代码的O(n)界慢

尽管如此,您仍然可以通过以下策略来扭转列表:

 Step 1: Split the list L into A (the first half) and B (the second half).
 Step 2: Recurse on each of A and B. This recursion should bottom out 
         when given a list of length 1.
 Step 3: Attach the new head of the reversed A to the new tail of the reversed B.

你可以看到,首先,我们的列表是AB。然后我们递归得到A'和B',每一个都是半列表的反向版本。然后输出新的反向列表B'A'。原始A的第一个元素现在是列表中的最后一个元素,原始B的最后一个元素现在是列表中的第一个元素。

这似乎真的很低效,你对它有实际用途吗,还是它只是一个练习?这只是一个看起来真的低效的练习,您对它有实际用途还是只是一个练习?这只是一个练习问题是,递归传递新列表的函数没有参数。大概您的函数可以将列表作为参数?否则它将如何反转列表?问题是,函数没有用于递归传递新列表的参数。假定您的函数允许将列表作为参数?否则它将如何扭转这一名单?