//Runtime: 30 ms
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == NULL) return NULL;
if (k == 1) return head;
ListNode *p1 = NULL, *p2 = NULL, *last = NULL, *next = head;
while (true){
p1 = next;
p2 = p1;
for (int i = 1; i < k; ++i){
if (p2 == NULL) break;
p2 = p2->next;
}
if (p2 == NULL) break;
next = p2->next;
ListNode *p1_ = p1;
ListNode *p2_ = p1_->next;
ListNode *p3_;
while (p2_ != next){
p3_ = p2_->next;
p2_->next = p1_;
p1_ = p2_;
p2_ = p3_;
}
if (last != NULL) last->next = p1_;
else head = p1_;
last = p1;
p1->next = next;
}
return head;
}
Reverse Nodes in k-Group
最新推荐文章于 2022-04-08 22:28:12 发布