题目
代码(首刷自解)
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next)
return head;
auto a = head;
auto b = head;
for(int i = 0; i < k; i++) {
if(!b)
return head;
b = b->next;
}
auto new_head = reverse(a, b);
a->next = reverseKGroup(b, k);
return new_head;
}
ListNode* reverse(ListNode* a, ListNode* b) {
if(a == b || a->next == b)
return a;
auto new_head = reverse(a->next, b);
a->next->next = a;
a->next = b;
return new_head;
}
};
代码(8.6 二刷调试看解析)
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
auto tail = head;
for(int i = 0; i < k; i++) {
if(!tail) {
return head;
}
tail = tail->next;
}
auto newHead = reverse(head, tail);
head->next = reverseKGroup(tail, k);
return newHead;
}
ListNode* reverse(ListNode* head, ListNode* tail) {
if(head == tail || head->next == tail)
return head;
auto newHead = reverse(head->next, tail);
head->next->next = head;
head->next =tail;
return newHead;
}
};
GO
func reverseKGroup(head *ListNode, k int) *ListNode {
tail := head
for i := 0; i < k; i++ {
if tail == nil {
return head
}
tail = tail.Next
}
newHead := reverse(head, tail)
head.Next = reverseKGroup(head.Next, k)
return newHead
}
func reverse(head, tail *ListNode) *ListNode {
if head == tail || head.Next == tail {
return head
}
newHead := reverse(head.Next, tail)
head.Next.Next = head
head.Next = tail
return newHead
}
代码(9.4 三刷自解)
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head)
return head;
auto cur = head;
for(int i = 0; i < k-1; i++) {
if(!cur || !cur->next)
return head;
cur = cur->next;
}
auto next = cur->next;
reverse(head, next);
head->next = reverseKGroup(next, k);
return cur;
}
ListNode* reverse(ListNode* head, ListNode* tail) {
if(head == tail || head->next == tail)
return head;
auto newHead = reverse(head->next, tail);
head->next->next = head;
head->next = tail;
return newHead;
}
};