写得不简洁,1h。总结一个清晰简洁的版本。
class Solution
{
public:
void reversList(ListNode* head, ListNode* tail, ListNode* prev_sec_tail, ListNode* next_sec_head)
{
if (!head)
{
return;
}
ListNode* head_origin = head;
ListNode* tail_origin = tail;
ListNode* curr = head;
ListNode* next = head->next;
ListNode* next_next = nullptr;
if (next)
{
next_next = next->next;
}
while (next)
{
next->next = curr;
if (next == tail)
{
break;
}
curr = next;
next = next_next;
if (next)
{
next_next = next->next;
}
}
head_origin->next = next_sec_head;
if (!prev_sec_tail)
{
prev_sec_tail = tail_origin;
}
else
{
prev_sec_tail->next = tail_origin;
}
prev_sec_tail = head_origin;
}
ListNode* reverseKGroup(ListNode* head, int k)
{
if (k < 2)
{
return head;
}
ListNode* curr_sec_head = head;
ListNode* curr_sec_tail = head;
ListNode* prev_sec_tail = nullptr;
ListNode* next_sec_head = nullptr;
bool is_get_final_head = false;
ListNode* final_head = head;
while (true)
{
int idx = 0;
while (idx < k - 1 && curr_sec_tail)
{
++idx;
curr_sec_tail = curr_sec_tail->next;
}
if (idx != k - 1 || !curr_sec_tail)
{
break;
}
else
{
next_sec_head = curr_sec_tail->next;
reversList(curr_sec_head, curr_sec_tail,prev_sec_tail,next_sec_head);
if (!is_get_final_head && curr_sec_tail)
{
final_head = curr_sec_tail;
is_get_final_head = true;
}
prev_sec_tail = curr_sec_head;
curr_sec_tail = next_sec_head;
curr_sec_head = next_sec_head;
}
}
return final_head;
}
};
2018-08-16 16:57:11 L.137'25369 T2925587773.K.F3783850860