//25. K 个一组翻转链表
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* ans = new ListNode(-1);
ans->next = NULL;
auto end = ans;
auto p = head;
int cnt = 0;
while (p != NULL) {
auto t = p;
p = p->next;
t->next = end->next;
end->next = t;
cnt++;
if (cnt == k) {
while (cnt) {
end = end->next;
cnt--;
}
}
}
if (cnt) {
p = end->next;
end->next = NULL;
while (p != NULL) {
auto t = p;
p = p->next;
t->next = end->next;
end->next = t;
}
}
return ans->next;
}
};
LeetCode25. K 个一组翻转链表
最新推荐文章于 2024-07-21 15:36:00 发布