当前位置:网站首页>【7.4】25. K 个一组翻转链表

【7.4】25. K 个一组翻转链表

2022-07-07 21:52:00 howtoloveyou

class Solution {
    
public:
	//反转一个链表并返回头尾节点
    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); //进行翻转并将head,tail赋予新的值
            pre->next = head; //将链表的头尾进行链接
            tail->next = nex;
            pre = tail;
            head = tail->next;
        }
        return hair->next;
    }
};
原网站

版权声明
本文为[howtoloveyou]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_38758049/article/details/125607088