【发布时间】:2021-03-27 08:12:10
【问题描述】:
如何在 java 中编写一个函数,通过将单链表分成两半来反转单链表,这意味着第一部分为 (n/2) 个节点,其余为第二部分(n 是喜欢列表的大小),直到它到达一个节点,然后合并这个分割的部分。在每个划分中允许使用两个新的链接列表,但不允许使用列表节点。该函数必须是void,并且该函数没有无参数。我有 n, head 和 tail 的主链表。
我在网站上找到了这段代码,但它没有将链接列表分成两半,所以它没有帮助。
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;
}
【问题讨论】:
-
这似乎效率很低,你有实际用途还是只是一个练习?
-
这只是一个练习
标签: java algorithm linked-list