题目:
25. Reverse Nodes in k-Group(hard)
解题思路:
递归 + 迭代的思路
递归求这K组,迭代求每段中链表的反转,这样思路比较清晰。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25java:
public ListNode reverseKGroup(ListNode head, int k) {
if(head == null ||head.next == null || k == 1) return head;
ListNode temp = head;
for(int i = 0; i < k; i++){
if(temp == null) return head;
temp = temp.next;
}
ListNode newHead = reverse(head,temp);
head.next = reverseKGroup(temp,k);
return newHead;
}
private ListNode reverse(ListNode head,ListNode tail){
ListNode pre = null;
ListNode next = null;
while(head != tail){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}