Leetcode 25. Un conjunto de listas vinculadas de K flip (método de simulación sin pretensiones)

El tiempo estará bueno el jueves 4 de marzo de 2021 [No lamentes el pasado, no desperdicies el presente, no temas el futuro]



1. Introducción

25. Un conjunto de listas enlazadas de K flip
Inserte la descripción de la imagen aquí

2. Solución de problemas (método de simulación)

Método de simulación sin pretensiones : la idea es similar a Leetcode 92. Invertir la lista vinculada II , pero es más complicado, debe invertir kun nodo de acuerdo con los nodos de cabeza y cola cada vez , y luego conectar el lugar roto hasta el resto. no hay suficientes nodos k.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
    
    
        if(k==1) return head;
        ListNode* hair = new ListNode(0);
        hair->next = head;
        ListNode* pre = hair;

        while(head){
    
    
            ListNode* cur = pre;
            // 查看剩余部分长度是否大于等于 k
            for(int i=0;i<k;++i){
    
    
                cur = cur->next;
                if(cur==nullptr)
                    return hair->next;         
            }
            ListNode* tail = cur;
            pair<ListNode*,ListNode*> p = reverseBetween(head,tail);
            head = p.first;
            tail = p.second;

            // 把子链表重新接回原链表
            pre->next = head;
            pre = tail;
            head = tail->next;
        }
        return hair->next;
    }

    // 翻转一个子链表,并且返回新的头与尾
    pair<ListNode*,ListNode*> reverseBetween(ListNode* head, ListNode* tail){
    
    
        ListNode* nex = head->next;
        ListNode* cur = head;
        while(cur!=tail){
    
    
            head->next = nex->next;
            nex->next = cur;
            cur = nex;
            nex = head->next;
        }
        return {
    
    tail,head};
    }
};

referencias

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/k-ge-yi-zu-fan-zhuan-lian-biao-by-leetcode-solutio/

Supongo que te gusta

Origin blog.csdn.net/m0_37433111/article/details/114361609
Recomendado
Clasificación