思路:
- 首先,我们根据k把链表分成,待翻转的链表,待翻转的前驱,待翻转的后继;
- 对需要翻转的部分翻转,然后更新指针,继续上一步,直到全部翻转完成。
翻转一组链表:递归实现。
- 递归函数返回的是已经翻转完成的链表;
- 递归函数要做的是把当前的节点head,连接到已经翻转完成的链表尾部;翻转完成后head刚好指向翻转后的尾部节点。
- 递归函数的返回条件是,节点为空或者节点的下一个为空。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode fake = new ListNode(0, head);
ListNode pre = fake;
ListNode end = pre;
while (head != null) {
for (int i = 0; i < k; i++) {
end = end.next;
if (end == null) {
return fake.next;
}
}
ListNode nextHead = end.next;
end.next = null;
ListNode temp = reverse(head);
pre.next = temp;
pre = head;
end = pre;
head = nextHead;
pre.next = head; // 记得链上所有的节点
}
return fake.next;
}
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp = reverse(head.next);
head.next.next = head;
head.next = null;
return temp;
}
}