Leetcode 25. K個のフリップリンクリストのセット(気取らないシミュレーション方法)

2021年3月4日木曜日は天気が良くなります[過去を嘆いたり、現在を無駄にしたり、未来を恐れたりしないでください]



1.はじめに

25.K個のフリップリンクリストのセット
ここに画像の説明を挿入

2.問題解決(シミュレーション方法)

気取らないシミュレーション方法:アイデアはLeetcode 92に似ています。リンクリストIIを逆にしますが、より複雑です。毎回ヘッドノードとテールkノードに従ってノードを反転し、壊れた場所を残りの部分まで接続する必要があります。十分なノードではありません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};
    }
};

参照

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

おすすめ

転載: blog.csdn.net/m0_37433111/article/details/114361609