/*本题方法类似与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 发布