/*本题方法类似与Swap Nodes in Pairs,直接遍历链表,先定位需要翻转的链表子段,然后将子段翻转即可。
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(head == nullptr || head->next == nullptr || k < 2) return head;
ListNode newHead(-1);
newHead.next = head;
ListNode *p(head->next), *q(head), *tmpHead(&newHead);
int count(0);
while(q != nullptr){
q = q->next;
if(++count == k){//该子段需要翻转,利用头插法即可
ListNode *tail(tmpHead->next);
while(p != q){
tail->next = p->next;
p->next = tmpHead->next;
tmpHead->next = p;
p = tail->next;
}
tmpHead = tail;
if(q == nullptr) break;
p = q->next;
count = 0;
}
}
return newHead.next;
}
};LeetCode之Reverse Nodes in k-Group
最新推荐文章于 2025-05-21 19:43:17 发布
本文介绍了一种链表操作算法——K组翻转。通过遍历链表并定位需要翻转的部分,采用头插法实现子链表的翻转。此方法类似于SwapNodesinPairs问题的解决方案。
852

被折叠的 条评论
为什么被折叠?



