当前位置:网站首页>【7.4】25. Turn over the linked list in groups of K

【7.4】25. Turn over the linked list in groups of K

2022-07-07 23:34:00 howtoloveyou

class Solution {
    
public:
	// Reverse a linked list and return the head and tail nodes 
    pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) {
     
        ListNode* prev = tail->next;
        ListNode* p = head;
        while (prev != tail) {
    
            ListNode* nex = p->next;
            p->next = prev;
            prev = p;
            p = nex;
        }
        return {
    tail, head};
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
    
        ListNode* hair = new ListNode(0);
        hair->next = head;
        ListNode* pre = hair;

        while (head) {
    
            ListNode* tail = pre;
            for (int i = 0; i < k; ++i) {
    
                tail = tail->next;
                if (!tail) {
    
                    return hair->next;
                }
            }
            ListNode* nex = tail->next;
            tie(head, tail) = myReverse(head, tail); // Flip and head,tail Assign a new value 
            pre->next = head; // Link the head and tail of the linked list 
            tail->next = nex;
            pre = tail;
            head = tail->next;
        }
        return hair->next;
    }
};
原网站

版权声明
本文为[howtoloveyou]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072057182423.html